I've seen both being used and so I wonder, do they do the same thing or different things? If it's the latter, what's the difference?
I tried answering it myself by having a look at the visual studio MVC 4 (rc) web api template, but sadly it uses both, so my confusion remains. Here's what the template contains:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
As the name implies, attribute routing uses [Route()] attribute to define routes. The Route attribute can be applied on any controller or action method. In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config. MapHttpAttributeRoutes() method.
If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.
Attribute routing Without this attribute the action will default back to convention-based routing. The RoutePrefixAttribute is an extensibility point that allows you more control of how you define your routes/Urls.
The default route template for the ASP.NET Web API application is “api/{controller}/{id}“. In this template, the term “api” is a literal path segment, and the {controller} and {id} are placeholder variables that will be replaced with the actual value.
Use RouteParameter
for Web Api routes (.MapHttpRoute
) and UrlParameter
for standard MVC controller routes (.MapRoute
). As you know standard MVC and Web API are 2 completely distinct APIs in terms of assemblies and namespaces even if both are pretty similar. You could for example self host your Web API in a console application, so you won't even have a reference to the System.Web.Mvc
assembly and you would of course use RouteParameter
in this case.
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