为什么 MapHttpAttributeRoutes() 不添加来自属性的路由?

Why MapHttpAttributeRoutes() does not add routes from attributes?

我有几个自己的控制器,路由基本上是由属性组成的。问题是,当我用 Postman 模拟我的 http 请求时,程序似乎不知道所提供的路由。

我的控制器看起来像这样:

[RoutePrefix("register")]
public class RegisterController : ApiController
{
    private readonly IRegisterService _service;

    public RegisterController(IRegisterService service)
    {
        _service = service;
    }

    [HttpPost]
    [Route("simple")]
    public void RegisterSimple(RegisterArgs args)
    {
        _service.RegisterSimple(args);
    }
}

请注意 Global.asax.cs 调用与 Web Api 2 兼容的配置:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);

        // DI Registrations
    }
}

... 和 WebApiConfig 调用 MapHttpAttributeRoutes() :

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

当我尝试使用 uri

从 Postman 调用 POST 方法时
http://localhost:63575/api/register/simple

我得到以下答案:

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:63575/api/register/simple'.",
    "MessageDetail": "No action was found on the controller 'Register' that matches the request."
}

我相信问题出在路由配置中。我调试了它,在两次方法调用(config.MapHttpAttributeRoutes() 和 config.Routes.MapHttpRoute)之后,配置只有两个路由:一个带有空 RouteTemplate (""),另一个由 MapHttpRoute() 调用提供("api/{controller}/{id}"). 我的问题是 - 如何通过属性正确配置路由?

您的控制器级路由前缀应以 "api" 开头,如下所示:

[RoutePrefix("api/register")]
public class RegisterController : ApiController