我正在尝试进行API调用
http://localhost:56578/v1/reports
调用我的GetReports()
方法。
但是,我继续在该主题中收到错误消息。
我通过路由前缀关注此处的ms docs:
我在做什么错了?
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 }
);
答案 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() {
//...
}
}