Different RoutePrefix, same controller name

陌路散爱 提交于 2019-12-22 01:39:20

问题


I'm having a problem with splitting my web-api application into different areas (not mvc areas), using namespaces and RoutePrefix

The application is hosted using Owin Self Host, and in my Startup class I have the following.

HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);

And my two controllers that I tested with

[RoutePrefix("api/test")]
public class TestController : ApiController
{
    [Route("")]
    public IHttpActionResult Get()
    {
        return Ok("api");
    }
}
[RoutePrefix("sync/test")]
public class TestController : ApiController
{
    [Route("")]
    public IHttpActionResult Get()
    {
        return Ok("sync");
    }
}

These two controllers live in two different namespaces, Api and Sync.

When I try to access the two controllers with http://localhost/api/test and http://localhost/api/sync I get a 404.

But If I rename one of the controllers to e.g. TestApiController then both works.

Someone having a good idea if it's possible to do what I want?


回答1:


Unfortunately, Web API finds controllers by class name, ignoring the namespace. This is a known issue and is not unique to attribute-based routing.

The easiest work-around by far is to avoid the problem and use unique controller names. But if you don't mind getting a little fancy, here's a solution:

https://blogs.msdn.microsoft.com/webdev/2013/03/07/asp-net-web-api-using-namespaces-to-version-web-apis/



来源:https://stackoverflow.com/questions/29627433/different-routeprefix-same-controller-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!