在控制器级别定义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 } ); } }
解决方法
请改用属性路由
public class DummyController : ApiController { // GET api/values [HttpGet] [Route("api/v2/dummy/get")] public IEnumerable<string> Get() { return new string[] { "value1","value3" }; } }
如果你想要路由前缀那么
[RoutePrefix("api/v2/dummy")] public class DummyController : ApiController { // GET api/v2/dummy [HttpGet] [Route("get")] public IEnumerable<string> Get() { return new string[] { "value1","value3" }; } }