Avoiding null model in ASP.Net Web API when no pos

2019-07-30 15:20发布

[HttpPost, Route("foo")]
public void DoStuff(FooModel args)
{
    if(args == null) args = new FooModel();

    // ...
}

public class FooModel
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

When a POST request is sent to a Web API method and the HTTP request does not include any of the arguments that would populate the model, instead of passing an empty model to the action, Web API instead just passes null to the action, necessitating a null check against the model argument at the start of every action.

I understand that the framework is probably trying to avoid an unnecessary object construction, but these are always lightweight classes with no specific functionality. It would save time and be more consistent if the model was constructed every time rather than trying to save some negligible fraction of a millisecond that would be the cost of just constructing the model object anyway and passing it to the action.

How can I get the framework to always pass a constructed (non-null) model object to my actions, even if none of the associated properties were able to be populated?

I'm using ASP.Net Web API 2.2.

1条回答
唯我独甜
2楼-- · 2019-07-30 16:11

The MVC Framework uses a system called model binding to create C# objects from HTTP requests in order to pass them as parameter values to action methods. This is how the MVC framework processes forms, for example: it looks at the parameters of the action method that has been targeted and uses a model binder to get the form values sent by the browser and convert them to the type of the parameter with the same name before passing them to the action method.

If you want to customize the way model binding works you can create a Custom Model Binder.

Parameter Binding in ASP.NET Web API

Creating a Custom Web API Model Binder

查看更多
登录 后发表回答