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

混江龙づ霸主 提交于 2019-12-10 01:52:32

问题


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 }
        );
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/11668925/should-i-use-routeparameter-or-urlparameter-for-an-asp-net-web-api-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!