Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure ASP.net Web API controller's parameter is not null?

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.

like image 306
guogangj Avatar asked Jan 25 '13 07:01

guogangj


People also ask

What is API controller in ASP NET Core?

API Controllers – Creating API in ASP.NET Core. API controllers are just like regular controllers except that their action methods produce responses which contain data objects and are sent to the client without HTML markup. Since not all clients are browsers so to provide them with data we your API Controllers.

What is the use of HTTP API controller?

It handles incoming HTTP requests and send response back to the caller. Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder. The name of a controller class must end with "Controller" and it must be derived from System.Web.Http.ApiController class.

What is parameter binding in ASP NET Web API?

Parameter Binding in ASP.NET Web API. When Web API calls a method on a controller, it must set values for the parameters, a process called binding. This article describes how Web API binds parameters, and how you can customize the binding process.

Why we must not create a web API controller by deriving?

You must not create a Web API controller by deriving from the Controller class is because the Controller class derives from ControllerBase class and adds support for views, so it’s for handling web pages, not web API requests.


1 Answers

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());
like image 189
guogangj Avatar answered Sep 17 '22 17:09

guogangj