Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

asp.net mvc - How does a method in MVC WebApi map to an http verb?

In the 5-minute video at the following link, at the 1:10 mark, Jon Galloway says that adding a method called DeleteComment to his CommentsController controller class will by convention map automatically to the delete http verb.

How does MVC with WebApi know how to rout the methods to the right verbs? I know the routing in the global.asax.cs file routes requests to the correct controller, but how does a delete request get "mapped by convention" to the delete method, or any method? Especially when there can be more than 1 method for each verb? "By convention" makes me think it's just looking at the first word in a method name ... but if so, it would have to read the signature of the methods to tell two delete methods or two get methods apart ... and where is all this defined?

Video: http://www.asp.net/web-api/videos/getting-started/delete-and-update

Thanks!

Edit: Here is the code in the sample ValuesController class that comes in the WebApi template. This was the source of my original question. How does the "convention" that differentiates between these (and any other methods in the controller) work?

// GET /api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET /api/values/5
    public string Get(int id)
    {
        return value;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I apologize in advance, this post strays a bit from what you asked, but all of this bubbled up when I read your question.

WebAPI Matching Semantic
The matching semantic used by (the default routes in) WebAPI is fairly simple.

  1. It matches the name of the action with the verb (verb = GET? look for method name starting with "get")
  2. if a parameter is passed, the api seeks an action with a parameter

So in your code sample a GET request without a parameter matches the Get*( ) function without an parameters. A Get containing and ID looks for a Get***(int id).

Examples
While the matching semantic is simple, it creates some confusion for MVC developers (well at least this developer). Lets look at some examples :

Odd Names - Your get method can be named anything, so long as it starts with "get". So in the case of a widget controller you can name your functions GetStrawberry() and it will still be matched. Think of the matching as something like : methodname.StartsWith("Get")

Multiple Matching Methods - What happens if you have two Get methods with no parameters? GetStrawberry() and GetOrange(). As best I can tell, the function defined first (top of the file) in your code wins ...strange. This has the side effect of making some methods in your controller unreachable (at least with the default routes)....stranger.

NOTE : the beta behaved as above for 'matching multiple methods' - the RC & Release version is a bit more OCD. It throws an error if there are multiple potential matches. This change removes the confusion of multiple ambiguous matches. At the same time, it reduces our ability to mix REST and RPC style interfaces in the same controller, relying on the order & overlapping routes.

What to do?
Well, WebAPI is new and consensus is still coalescing. The community seems to be reaching for REST principles quite a bit. Yet, not every API can or should be RESTful, some are more naturally expressed in an RPC style. REST & what people call REST seems to be the source of quite a bit of confusion, well at least to Roy Fielding.

As a pragmatist, i suspect that many API's will be 70% RESTful, with a smattering of RPC style methods. First, the the controller proliferation alone (given the webapi binding method) is going to drive developers bonkers. Second, WebAPI doesn't really have a built in way to create a nested structure of api paths (meaning: /api/controller/ is easy, but /api/CATEGORY/Sub-Category/Controller is doable, but a pain).

From my perspective, I would love to see the webAPI folder structure control the default API paths... meaning if I create a Category folder in my UI project then /api/Category would be the default path (something parallel to this MVC article).

What did I do?
So, I had a few requirements: (1) to be able to use restful syntax in most case, (2) have some "namespace" separation of controllers (think sub-folders), (3) be able to call additional rpc-like methods when necessary. Implementing these requirements came down to clever routing.

// SEE NOTE AT END ABOUT DataToken change from RC to RTM

Route r;
r = routes.MapHttpRoute( name          : "Category1", 
                         routeTemplate : "api/Category1/{controller}/{id}", 
                         defaults      : new { id = RouteParameter.Optional } );
r.DataTokens["Namespaces"] = new string[] {" UI.Controllers.Category1"};

r = routes.MapHttpRoute( name          : "Category2", 
                         routeTemplate : "api/Category2/{controller}/{id}", 
                         defaults      : new { id = RouteParameter.Optional } );
r.DataTokens["Namespaces"] = new string[] {" UI.Controllers.Category2"};

routes.MapHttpRoute(     name          : "ApiAllowingBL", 
                         routeTemplate : "api/{controller}/{action}/{id}",
                         defaults      : new { id = RouteParameter.Optional } );

routes.MapHttpRoute(     name          : "DefaultApi",  
                         routeTemplate : "api/{controller}/{id}",           
                         defaults      : new { id = RouteParameter.Optional } );
  • The first two routes create "sub-folder" routes. I need to create a route for each sub-folder, but I limited myself to major categories, so I only end up with 3-10 of these. Notice how these routes add the Namespace data token, to restrict what classes are searched for a particular route. This corresponds nicely to the typical namespace setup as you add folders to a UI project.
  • The third route allows specific method names to be called (like traditional mvc). Since web API does away with action name in the URL, it's relatively easy to tell which calls want this route.
  • The last route entry is the default web api route. This catches any classes, particularly ones outside my 'sub-folders'.

Said Another Way
My solution came down to down to separating controllers a bit more so /api/XXXX didn't get too crowded.

  • I create a folder in my UI project(lets say Category1), and put api controllers within the folder.
  • Visual studio naturally sets class namespaces based on folder. So Widget1 in the Category1 folder gets a default namespace of UI.Category1.Widget1.
  • Naturally, I wanted api URLs to reflect the folder structure (/api/Category1/Widget). The first mapping you see above accomplishes that, by hard coding /api/Category1 into the route, then the namespace token restricts classes that will be searched for a matching controller.

NOTE: as of the release DataTokens are null by default. I'm not sure if this is a bug, or a feature. So I wrote a little helper method and added to my RouteConfig.cs file....

r.AddRouteToken("Namespaces", new string[] {"UI.Controllers.Category1"});

private static Route AddRouteToken(this Route r, string key, string[] values) {
  //change from RC to RTM ...datatokens is null
if (r.DataTokens == null) {
       r.DataTokens = new RouteValueDictionary();
    }
    r.DataTokens[key] = values;
    return r;
}

NOTE 2: even thought this is a WebAPI 1 post, as @Jamie_Ide points out in the comments the above solution doesn't work in WebAPI 2 because IHttpRoute.DataTokens has no setter. To get around this you can use a simple extension method like this:

private static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, string[] namespaceTokens)
{   
    HttpRouteValueDictionary    defaultsDictionary      = new HttpRouteValueDictionary(defaults);
    HttpRouteValueDictionary    constraintsDictionary   = new HttpRouteValueDictionary(constraints);
    IDictionary<string, object> tokens                  = new Dictionary<string, object>();
                                tokens.Add("Namespaces", namespaceTokens);

    IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: tokens, handler:null);
    routes.Add(name, route);

    return route;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...