删除"api" Web API URL中的前缀 [英] Remove "api" prefix from Web API url
问题描述
我有一个API控制器
public class MyController : ApiController { ... }
默认情况下,它映射到URL mysite/api/My/Method
,我希望它具有不带"api"前缀的URL:mysite/My/Method
By default it is mapped to URL mysite/api/My/Method
, and I'd like it to have URL without "api" prefix: mysite/My/Method
设置控制器属性[RoutePrefix("")]
对我没有帮助.
Setting controller attribute [RoutePrefix("")]
didn't help me.
还有其他方法可以实现吗?
Are there any other ways to achieve that?
推荐答案
默认注册通常在WebApiConfig
中找到,并且往往看起来像这样
The default Registration is usually found in WebApiConfig
and tends to look like this
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
您需要在基于约定的设置中编辑routeTemplate
.
You need to edit the routeTemplate
in the convention-based setup.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
请注意,如果此项目与MVC共享,则api
前缀的原因是为了避免两个框架之间的路由冲突.如果仅使用Web API,那么应该没有问题.
Do note that if this project is shared with MVC that the reason for the api
prefix was to avoid route conflicts between the two frameworks. If Web API is the only thing being used then there should be no issue.
这篇关于删除"api" Web API URL中的前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!