Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use RouteParameter or UrlParameter for an Asp.NET web-api route?

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 }
        );
    }
}
like image 422
Gaute Løken Avatar asked Jul 26 '12 12:07

Gaute Løken


People also ask

Which method is generally used for registering Web API routes?

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.

What is the difference between MVC routing vs Web API routing?

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.

What is difference between route and Routeprefix?

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.

What is the default route template in Web API?

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.


1 Answers

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.

like image 98
Darin Dimitrov Avatar answered Oct 18 '22 01:10

Darin Dimitrov