Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of [Bind(Prefix = "principalId")] in MVC4 Web Api?

Background:

In MVC3, I've used the following syntax to specify custom Action parameter names:

public ActionResult ActionName([Bind(Prefix = "principalID")] int userID,
                               [Bind(Prefix = "dependentID")] long applicationID)

The route for this action was defined as follows (ActionNameConstraint is a custom IRouteConstraint):

routes.MapHttpRoute(
    "DependantAction",
    "{controller}/{principalID}/{action}/{dependentID}",
    new {controller = @"[^0-9]+", action = ActionNameConstraint.Instance, dependentID = RouteParameter.Optional}
    );

Question:

The BindAttribute is a System.Web.Mvc class. Is there an equivalent of this (parameter binding) in Web Api?

Of course, if there are other solutions to achieve the same result, I'd love to hear them!

like image 379
sazh Avatar asked Apr 26 '12 23:04

sazh


People also ask

How do I bind data in Web API?

Easiest way is to add ModelBinder attribute to the parameter. In following example, I have added ModelBinder attribute to the "data" parameter, so web API can understand how to use custom model binder, while binding the data. Another way is to add ModelBinder attribute to the type.

What is model bindings in Web API?

Model Binding is the most powerful mechanism in Web API 2. It enables the response to receive data as per requester choice. i.e. it may be from the URL either form of Query String or Route data OR even from Request Body. It's just the requester has to decorate the action method with [FromUri] and [FromBody] as desired.

What is bind attribute in MVC?

Bind Attribute The [Bind] attribute will let you specify the exact properties of a model should include or exclude in binding. In the following example, the Edit() action method will only bind StudentId and StudentName properties of the Student model class.

What is FromBody attribute?

The [FromBody] attribute which inherits ParameterBindingAttribute class is used to populate a parameter and its properties from the body of an HTTP request. The ASP.NET runtime delegates the responsibility of reading the body to an input formatter.


1 Answers

You can use the System.Web.Http.FromUriAttribute attribute to specify the parameter names used for model binding.

public ActionResult ActionName(
                    [FromUri(Name = "principalID.userID")] int userID,
                    [FromUri(Name= "dependentID.applicationID")] long applicationID
                    )

FromUri tells model binding to examine the query string and the RouteData for the request.

like image 65
Steve Ruble Avatar answered Oct 17 '22 21:10

Steve Ruble