在控制器级别定义RoutePrefix时,当我尝试使用前缀为http://localhost:55020/api/v2/dummy/get
的URL访问API类时,它会抛出404.虽然这个http://localhost:55020/api/dummy/get
工作正常。
这是控制器类,其中定义了RoutePrefix
[RoutePrefix("v2/dummy")]
public class DummyController : ApiController
{
// GET api/values
[SwaggerOperation("Get")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2", "value3" };
}
}
这是WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
答案 0 :(得分:7)
使用属性路由
testing
如果你想要路由前缀,那么
public class DummyController : ApiController
{
// GET api/values
[HttpGet]
[Route("api/v2/dummy/get")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2", "value3" };
}
}
答案 1 :(得分:2)
您正在混淆属性路由和基于约定的路由的工作方式。
这是完整的属性路由。
[RoutePrefix("api/v2/dummy")]
public class DummyController : ApiController
{
// GET api/v2/dummy/get
[HttpGet]
[Route("get")]
[SwaggerOperation("Get")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2", "value3" };
}
}
如果你想通过基于约定的路由做同样的事情
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DummyApi",
routeTemplate: "api/v2/dummy/{action}",
defaults: new { controller = "Dummy" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}