问题
I'm working with Web API 2, and it seems to pull up my existing API calls already, except it's duplicating all the calls for each area that i have. For example, say i have 3 areas, and in one of those i have an API call that looks like:
public IList<string> GetStringList(string id)
{
//do work here...
return new List<string>{"a","b","c"};
}
if i have 3 areas, then the web api help page will show:
GET area1/api/MyAPIController/GetStringList/{id}
GET area2/api/MyAPIController/GetStringList/{id}
GET area3/api/MyAPIController/GetStringList/{id}
and the MyAPIController only exists in 'area2'. Why is this showing 3 times, and how can i fix it? If it helps, my area registration for area2 is:
public class Area2AreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Area2";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Area2_default",
"Area2/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
context.Routes.MapHttpRoute(
name: "Area2_ActionApi",
routeTemplate: "Area2/api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
回答1:
While not a solution to your problem, you can use attributes to map the routes for actions as a temporary workaround.
To enable attributes for routing add config.MapHttpAttributeRoutes(); to the registration in WebApiConfig, which should be within the App_Start folder.
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Once you've enabled attribute routing you can specify a route over an action:
public class BooksController : ApiController
{
[Route("api/books")]
public IEnumerable<Book> GetBooks() { ... }
}
You can read more here. Take a look at route prefixes(shown above) and make sure you enable routing with attributes as shown in the beginning of the page.
Edit:
In your case:
[Route("area2/api/MyAPIController/GetStringList/{id}")]
public IList<string> GetStringList(string id)
{
//do work here...
return new List<string>{"a","b","c"};
}
来源:https://stackoverflow.com/questions/29441248/web-api-help-page-duplicating-action-for-all-areas