12

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!

tereško
  • 58,060
  • 25
  • 98
  • 150
sazh
  • 1,792
  • 15
  • 20

2 Answers2

5

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.

Steve Ruble
  • 3,875
  • 21
  • 27
-2

I understand that in WebAPI you just use special controller class base, and special Action names, but still after all they are controllers and actions.

Did you try it and it didn't work? A quick look at this article seems to suggest model binding in general (not the specific attribute though) should work normally:

http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

Edit:

Some say this should work with MVC only and downvoted the answer. Here you go, more references:

Community
  • 1
  • 1
Meligy
  • 35,654
  • 11
  • 85
  • 109
  • I did review that article actually, it doesn't really hit the same intent - the article is mainly covering model binding (most of my searches have led to results about model binding actually) – sazh Apr 27 '12 at 00:29
  • 1
    ASP.NET Web API doesn't have a `BindAttribute` functionality built in. The action parameter binding is done my model binding and formatting feature of Web API. So, it is not just model binders. Another tip here is that: do not use anything under `System.Web.Mvc` namespace with ASP.NET Web API. 99% of the time, you will be in trouble if you do this. – tugberk Jun 20 '12 at 14:59