Web API 2 RoutePrefix 不工作

Web API 2 RoutePrefix does not working

在控制器级别定义 RoutePrefix 时,当我尝试使用前缀为 http://localhost:55020/api/v2/dummy/get 的 URL 访问 API class 时,它会抛出 404。这 http://localhost:55020/api/dummy/get 虽然工作得很好。

这是控制器class,它定义了 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", "value2", "value3" };
    }
}

如果你想要路由前缀那么

[RoutePrefix("api/v2/dummy")]
public class DummyController : ApiController
{
    // GET api/v2/dummy
    [HttpGet]
    [Route("get")]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2", "value3" };
    }
}

您混淆了属性路由和基于约定的路由的工作方式。

这是全属性路由。

[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 }
        );
    }
}