问题
I've the following problem, my route attribute is not working.
I have the following action:
[HttpGet]
[Route("~api/admin/template/{fileName}")]
public HttpResponseMessage Template(string fileName)
{
return CreateHtmlResponse(fileName);
}
and i want to access the action like .../api/admin/template/login.html
, so that Template get login.html passed as the file name.
But i alsways get: No HTTP resource was found that matches the request URI 'http://localhost:50121/api/admin/template/login.html'
.
The following request works: /api/admin/template?fileName=login.html
Does anyone know, what i am doing wrong with my routing?
EDIT:
My route configuration
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{action}",
new { id = RouteParameter.Optional });
回答1:
You have to call MapHttpAttributeRoutes()
so that the Framework will be able to walk through your attributes and register the appropriate routes upon application start:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
// you can add manual routes as well
//config.Routes.MapHttpRoute(...
}
}
See MSDN
回答2:
try adding a forward slash after the tilde
[HttpGet]
[Route("~/api/admin/template/{fileName}")]
public HttpResponseMessage Template(string fileName)
{
return CreateHtmlResponse(fileName);
}
回答3:
Check your Route attribute's namespace. It should be System.Web.Http instead of System.Web.Mvc.
回答4:
Verify that you are using System.Web.Http.RouteAttribute
and not System.Web.Mvc.RouteAttribute
回答5:
Try this routing in your WebApiConfig
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
You have to add RoutePrefix
.
回答6:
With my Web API 2 project I had to add a [RoutePrefix("events")]
to the controller for it to pickup the action route attribute.
回答7:
In my case, I added Route("api/dashboard")
to api controller.
Changed it to RoutePrefix("api/dashboard")
. And it works perfectly.
Also you need config.MapHttpAttributeRoutes();
in webapiconfig.cs
来源:https://stackoverflow.com/questions/28067419/asp-net-web-api-2-route-attribute-not-working