How to ensure ASP.net Web API controller's par

2019-06-16 19:56发布

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;
        //...
    }
}

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.

2条回答
Anthone
2楼-- · 2019-06-16 20:27

Finally, I got the solution:

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

And...

//In Application_Start()
GlobalConfiguration.Configuration.Filters.Add(new ModelValidateFilterAttribute());
查看更多
干净又极端
3楼-- · 2019-06-16 20:34

This post has details about how to create the action filter and register it globally:

http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

It's at the bottom of the page.

查看更多
登录 后发表回答