不同的RoutePrefix,相同的控制器名称 [英] Different RoutePrefix, same controller name
问题描述
使用命名空间和RoutePrefix将我的Web-api应用程序划分到不同区域(不是mvc区域)时遇到问题
I'm having a problem with splitting my web-api application into different areas (not mvc areas), using namespaces and RoutePrefix
该应用程序是使用Owin Self Host托管的,在我的Startup类中,我有以下内容.
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");
}
}
这两个控制器位于两个不同的命名空间Api和Sync中.
These two controllers live in two different namespaces, Api and Sync.
当我尝试使用以下命令访问两个控制器时 http://localhost/api/test 和 http://localhost/api/sync 我得到一个404.
When I try to access the two controllers with http://localhost/api/test and http://localhost/api/sync I get a 404.
但是如果我将其中一个控制器重命名为然后,TestApiController都可以工作.
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?
推荐答案
不幸的是,Web API通过类名称查找控制器,而忽略了名称空间.这是一个已知问题,并非基于属性的路由独有.
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:
这篇关于不同的RoutePrefix,相同的控制器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!