c# – 当Web API中没有发布数据时,避免使用null模型
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 当Web API中没有发布数据时,避免使用null模型,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2309字,纯文字阅读大概需要4分钟。
内容图文
![c# – 当Web API中没有发布数据时,避免使用null模型](/upload/InfoBanner/zyjiaocheng/804/3ca94cea1c2642d5b92aba601902e042.jpg)
这个问题类似于我想要实现的目标:
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中使用所有默认模型绑定,但我想避免使用null对象.
我不相信模型绑定可以解决我的问题.
这更接近我想要做的事情,除了它的每种类型,这是乏味的.
解决方法:
编辑:由于问题是Web API,我也在下面发布Web API解决方案.
您可以在动作过滤器中执行以下操作.仅当您的模型包含默认构造函数时,以下代码才有效.
Web 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);
}
内容总结
以上是互联网集市为您收集整理的c# – 当Web API中没有发布数据时,避免使用null模型全部内容,希望文章能够帮你解决c# – 当Web API中没有发布数据时,避免使用null模型所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。