这个问题与我想要实现的目标类似:
当没有发布的属性与模型匹配时,避免在 ASP.Net Web API 中使用 null 模型 https://stackoverflow.com/questions/25160345/avoiding-null-model-in-asp-net-web-api-when-no-posted-properties-match-the-model
但它没有得到答复。
我有一条路线采用 GET 模型:
[HttpGet, Route("accounts")]
public AccountListResult Post(AccountListRequest loginRequest)
{
return accountService.GetAccounts(loginRequest);
}
该模型填充有来自操作过滤器的附加数据。
在这种情况下,需要知道的只是 UserId,操作过滤器将其添加到基于随请求传入的 cookie/标头的模型中。
我想使用 WebAPI 中的所有默认模型绑定,但我想避免空对象。
我不相信模型绑定可以解决我的问题。
如何替换 Web API 模型绑定的行为,以便在没有传入参数时收到一个新实例而不是 Null https://stackoverflow.com/questions/26527492/how-do-i-replace-the-behaviour-of-web-api-model-binding-so-that-instead-of-null
这更接近我想要做的事情,除了它的每种类型都很乏味。
编辑:由于问题是针对 Web API 的,因此我也在下面发布了 Web API 解决方案。
您可以在操作过滤器中按如下方式执行此操作。仅当您的模型包含默认构造函数时,以下代码才有效。
网络 API 实现:
public override void OnActionExecuting(HttpActionContext actionContext)
{
var parameters = actionContext.ActionDescriptor.GetParameters();
foreach (var parameter in parameters)
{
object value = null;
if (actionContext.ActionArguments.ContainsKey(parameter.ParameterName))
value = actionContext.ActionArguments[parameter.ParameterName];
if (value != null)
continue;
value = CreateInstance(parameter.ParameterType);
actionContext.ActionArguments[parameter.ParameterName] = value;
}
base.OnActionExecuting(actionContext);
}
protected virtual object CreateInstance(Type type)
{
// Check for existence of default constructor using reflection if needed
// and if performance is not a constraint.
// The below line will fail if the model does not contain a default constructor.
return Activator.CreateInstance(type);
}
MVC 实现:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var parameters = filterContext.ActionDescriptor.GetParameters();
foreach (var parameter in parameters)
{
if (filterContext.ActionParameters.ContainsKey(parameter.ParameterName))
{
object value = filterContext.ActionParameters[parameter.ParameterName];
if (value == null)
{
// The below line will fail if the model does not contain a default constructor.
value = Activator.CreateInstance(parameter.ParameterType);
filterContext.ActionParameters[parameter.ParameterName] = value;
}
}
}
base.OnActionExecuting(filterContext);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)