避免空模型在ASP.Net的Web API时没有发表任何属性的模型匹配 [英] Avoiding null model in ASP.Net Web API when no posted properties match the model

查看:143
本文介绍了避免空模型在ASP.Net的Web API时没有发表任何属性的模型匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[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; }
}

当一个POST请求被发送到一个Web API方法和HTTP请求不包括任何将填充,而不是传递一个空模型来操作的模型,参数,网页API而不是仅仅传递空的动作在每一个动作的开始迫使对模型参数的空检查。

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?

我使用ASP.Net的Web API 2.2。

I'm using ASP.Net Web API 2.2.

推荐答案

MVC框架使用一种称为模型绑定创建从HTTP请求C#对象,以传递系统
它们作为参数值的操作方法。这就是MVC框架如何处理形式,例如:它看起来
在已针对性和使用模型绑定来获取表单值发送的动作方法的参数
由浏览器,并将其转换为具有相同名称的参数的类型将它们​​传递到动作前
方法。

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.

<一个href=\"http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api\"相对=nofollow>参数中的ASP.NET Web API 绑定

创建自定义的Web API模型绑定

这篇关于避免空模型在ASP.Net的Web API时没有发表任何属性的模型匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆