简体   繁体   中英

Different RoutePrefix, same controller name

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 eg TestApiController then both works.

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM