问题
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