Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 668
Jens-Christian Skibakk Avatar asked Apr 14 '15 12:04

Jens-Christian Skibakk


1 Answers

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/

like image 173
Todd Menier Avatar answered Oct 06 '22 00:10

Todd Menier