Web Api Route 注册要放在 Mvc Route 注册前

2020-11-20 22:09

阅读:727

标签:style   blog   class   code   java   color   

今天想研究一下Web Api,写了一个测试Api,打开网站后浏览一下,可是却提示找不到方法,刚开始以为哪里配置错了,可找了半天也没见。

因为我是在一个现有Mvc站点做的Demo,所以打算新建一个Mvc网站,再试一下,新站点是正常的,对比一下Global文件,发现WebApiConfig和RouteConfig顺序不一样。

如果把新站点的RouteConfig也放在WebApiConfig之前,同样提示找不到方法。看来这两个配置有关联呀。

?
1
2
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);

  看了一下GlobalConfiguration类就明白了

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static class GlobalConfiguration
{
    private static Lazy _configuration = new Lazy(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;
        }
    }
     
   //...
}

  

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 }
           );
       }
   }

  合并后的类似路由:

soscw.com,搜素材
 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             );
soscw.com,搜素材

 

如果顺序反了,DefaultApi的路由就永远匹配不到了,会一直找MVC的路由"{api}/{action}/{id}"。

Web Api Route 注册要放在 Mvc Route 注册前,搜素材,soscw.com

Web Api Route 注册要放在 Mvc Route 注册前

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/lizhanglong/p/3710567.html


评论


亲,登录后才可以留言!