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!
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With