路由错误:找不到与请求URI匹配的HTTP资源

时间:2019-04-05 20:56:20

标签: c# asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

我正在尝试进行API调用

  

http://localhost:56578/v1/reports

调用我的GetReports()方法。

但是,我继续在该主题中收到错误消息。

我通过路由前缀关注此处的ms docs:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-prefixes

我在做什么错了?

ReportV1Controller.cs

[Authorize]
[RoutePrefix("v1/reports")]
....
....
[Route("")]
public IHttpActionResult GetReports()

WebApiConfig.cs

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

2 个答案:

答案 0 :(得分:1)

从此更改:

[RoutePrefix("v1/reports")]

对此:

[RoutePrefix("api/v1/reports")]

由于:

config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

请参阅routeTemplate: "api/{controller}/{action}/{id}",您说所有路径的前缀将为api{controller}/{action}/{id}是占位符

结论:如果要在所有地方使用v1前缀,请使用它代替api

答案 1 :(得分:0)

如果您已在WebApiConfig

中启用了属性路由,那么您应该拥有的东西就可以工作
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes(); //<-- THIS HERE

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

引用Attribute Routing in ASP.NET Web API 2: Enabling Attribute Routing

并假设

[Authorize]
[RoutePrefix("v1/reports")]
public class ReportV1Controller : ApiController {

    //GET v1/reports
    [Route("")]
    [HttpGet]
    public IHttpActionResult GetReports() {
        //...
    }
}