4

If I create a webApi controller, and populate it with methods prefixed with http verbs, the Api is able to correctly imply what verb should be used on that controller.

public class TestController : ApiController
{
    public string GetData()
    {
        return "Called Get Method";
    }

    public string PostData()
    {
        return "Called Post Method";
    }

    public string PutData()
    {
        return "Called Put Method";
    }
}

If I replace the Post with Update, the Post method continues to work implicitly.

public string UpdateData()
{
    return "Called Updated Method";
}

Is there a list of the possible prefixes on a method and what verb they map to? Additionally, is it possible to define custom prefixes? For instance, if I wanted to always map a method starting with "Search" to a Post, can I define this?

Obsidian Phoenix
  • 4,083
  • 1
  • 22
  • 60

2 Answers2

2

If you put your Routing like the following :

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

Consider the routeTemplate.You'll now be able to call the actions on the controller by name,and no prefix issue should exist. This approach is very helpful if you have multiple actions on your controller with similar HTTP Verbs(multiple GET or POST say).

Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24
2

Implicit Verbs are a function of the built in routing, and cannot appear to be manually extended.

This Asp.Net details the specific rules around the implicit routing.

HTTP Methods. The framework only chooses actions that match the HTTP method of the request, determined as follows:

  1. You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
  2. Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
  3. If none of the above, the method supports POST.

The reason why the UpdateData method appears to work, is because any method not implicitly determined is automatically a Post

Obsidian Phoenix
  • 4,083
  • 1
  • 22
  • 60
  • I was trying to figure out how the template AccountController was determining GET vs. POST. Extremely helpful, thank you! – Dan Bechard Apr 20 '16 at 18:06