Web Api Route 注册要放在 Mvc Route 注册前
2020-11-20 22:09
标签:style blog class code java color 今天想研究一下Web Api,写了一个测试Api,打开网站后浏览一下,可是却提示找不到方法,刚开始以为哪里配置错了,可找了半天也没见。 因为我是在一个现有Mvc站点做的Demo,所以打算新建一个Mvc网站,再试一下,新站点是正常的,对比一下Global文件,发现WebApiConfig和RouteConfig顺序不一样。 如果把新站点的RouteConfig也放在WebApiConfig之前,同样提示找不到方法。看来这两个配置有关联呀。 看了一下GlobalConfiguration类就明白了 合并后的类似路由: 如果顺序反了,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
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
public
static
class
GlobalConfiguration
{
private
static
Lazy
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;
}
}
//...
}
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 );
上一篇:panel内嵌程序窗体
下一篇:python之socket模块
文章标题:Web Api Route 注册要放在 Mvc Route 注册前
文章链接:http://soscw.com/essay/22033.html