今天想研究一下Web Api,写了一个测试Api,打开网站后浏览一下,可是却提示找不到方法,刚开始以为哪里配置错了,可找了半天也没见。
因为我是在一个现有Mvc站点做的Demo,所以打算新建一个Mvc网站,再试一下,新站点是正常的,对比一下Global文件,发现WebApiConfig和RouteConfig顺序不一样。
如果把新站点的RouteConfig也放在WebApiConfig之前,同样提示找不到方法。看来这两个配置有关联呀。
WebApiConfig.Register(GlobalConfiguration.Configuration); RouteConfig.RegisterRoutes(RouteTable.Routes);
看了一下GlobalConfiguration类就明白了
public static class GlobalConfiguration { private static Lazy<HttpConfiguration> _configuration = new Lazy<HttpConfiguration>(delegate { HttpConfiguration configuration = new HttpConfiguration(new HostedHttpRouteCollection(RouteTable.Routes)); configuration.Services.Replace(typeof(IAssembliesResolver), new WebHostAssembliesResolver()); configuration.Services.Replace(typeof(IHttpControllerTypeResolver), new WebHostHttpControllerTypeResolver()); configuration.Services.Replace(typeof(IHostBufferPolicySelector), new WebHostBufferPolicySelector()); return configuration; }); public static HttpConfiguration Configuration { get { return _configuration.Value; } } //... }
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "t/{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
合并后的类似路由:
1 routes.MapHttpRoute( 2 name: "DefaultApi", 3 routeTemplate: "api/{controller}/{id}", 4 defaults: new { id = RouteParameter.Optional } 5 ); 6 routes.MapRoute( 7 name: "Default", 8 url: "{controller}/{action}/{id}", 9 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 10 );
如果顺序反了,DefaultApi的路由就永远匹配不到了,会一直找MVC的路由"{api}/{action}/{id}"。