问题
I'm trying to make the API call
http://localhost:56578/v1/reports
to call my GetReports()
method.
However I continue to get the error message in the subject.
I'm following the ms docs here via the route prefix:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-prefixes
What am I doing wrong?
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 }
);
回答1:
Change from this:
[RoutePrefix("v1/reports")]
to this:
[RoutePrefix("api/v1/reports")]
because of:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
See routeTemplate: "api/{controller}/{action}/{id}"
, you said prefix for all paths will be api
, {controller}/{action}/{id}
are placeholders
Conclusion: if you are going to use v1
prefix everywhere, put it instead of api
回答2:
What you have should work provided that you have enabled attribute routing in the 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 }
);
}
}
Reference Attribute Routing in ASP.NET Web API 2: Enabling Attribute Routing
And assuming
[Authorize]
[RoutePrefix("v1/reports")]
public class ReportV1Controller : ApiController {
//GET v1/reports
[Route("")]
[HttpGet]
public IHttpActionResult GetReports() {
//...
}
}
来源:https://stackoverflow.com/questions/55543249/routing-error-no-http-resource-was-found-that-matches-the-request-uri