如何保证ASP.net的Web API控制器的参数不为空? [英] How to ensure ASP.net Web API controller's parameter is not null?
本文介绍了如何保证ASP.net的Web API控制器的参数不为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个ASP.net的Web API控制器这样的:
I created a ASP.net Web API controller like that:
public class UsersController : ApiController
{
//...
public void Put([FromBody]User_API user, long UpdateTicks)
{
user.UpdateTicks = UpdateTicks;
//...
}
}
用户参数将是空如果客户不提供正确的参数。我可以做一个全球性的过滤器来检查这样的每一个参数,并且如果发生任何错误都会返回400消息。
The "user" parameter will be null if the client does not provide correct arguments. Can I make a global filter to check every parameter like this, and will return a 400 message if any error occurs.
推荐答案
最后,我得到了解决:
public class ModelValidateFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ActionArguments.Any(v => v.Value==null))
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}
和...
//In Application_Start()
GlobalConfiguration.Configuration.Filters.Add(new ModelValidateFilterAttribute());
这篇关于如何保证ASP.net的Web API控制器的参数不为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文