Cru*_*ler 5 c# asp.net-web-api asp.net-web-api-routing
我有一个webforms应用程序,其中有一些Web Api控制器用于集成.两个工作正常.但今天我想添加另一个控制器.
应该很简单,我添加一个新的Web Api控制器,向它添加一些代码,并且:
namespace MyApp.Web.App_Code
{
public class AuthExportController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我在这个网址上调用它时:
http://localhost:30978/MyApp/api/AuthExport
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Multiple types were found that match the controller named
'AuthExport'. This can happen if the route that services this request
('api/{controller}/{id}') found multiple controllers defined with the same name but
differing namespaces, which is not supported. The request for 'AuthExport' has found
the following matching controllers: MyApp.Web.App_Code.AuthExportController
MyApp.Web.App_Code.AuthExportController</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace> at
System.Web.Http.Dispatcher.DefaultHttpControllerSelector.SelectController(HttpRequestMessag
e request) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage
request, CancellationToken cancellationToken) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken)</StackTrace>
</Error>
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,它抱怨2个控制器具有相同的名称,但它是完全相同的控制器.我的其他控制器工作正常,只是这个特别的.
如果它有帮助,这是我在global.asax中的路由代码
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());
}
Run Code Online (Sandbox Code Playgroud)
让我生气!
更新:
好的,我设法修复它,但我不明白为什么,所以如果有人可以向我解释.我比较了我的工作控制器和我的工作控制器.完全相同的签名,没有什么不同,使用语句,相同的继承等等.我注意到的一件事是对文件的构建操作.工作文件具有"内容"的构建操作,而非工作文件具有"编译"的构建操作.我将我的非工作一个更改为"内容",它的工作原理.
所以现在我更加困惑:)很高兴它有效,但我不喜欢我的系统中的黑魔法
Dov*_*kas 28
TL; DR:
删除bin项目文件目录中的文件夹,然后重新构建项目.
说明:
我刚刚在重命名现有项目并更改其名称空间时遇到此错误,这就是发生的事情:
假设项目的名称是FirstName,我想将其重命名为SecondName.
bin/Debug/FirstName.dll文件的项目SecondNamebin/Debug/SecondName.dll当项目运行时,IIS Express只是将所有.dll文件都加载到内存中,这恰好包含了两个FirstName.dll和SecondName.dll.
正如您可能已经理解的那样,FirstName.dll并且SecondName.dll具有相同的类和方法,但具有不同的命名空间!因此,由于两个DLL都是由IIS加载到内存中的,因此WebApi路由机制正在查找具有相同控制器和操作名称的两个命名空间.
你有它.毕竟没有伏都教魔法:)
| 归档时间: |
|
| 查看次数: |
7471 次 |
| 最近记录: |