【问题标题】:Exception could not load assembly Cors异常无法加载程序集 Cors
【发布时间】:2025-12-08 06:55:02
【问题描述】:

我正在我的应用程序中开发一个 webApi。我有一个奇怪的问题。我试图在一个独立的控制台应用程序中做这个项目,一切运行良好。我的问题是当我尝试在另一个大型应用程序中加载该 Web api 时。我收到此错误:

无法加载文件或程序集“Microsoft.Owin,Version=3.0.1.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35”或其依赖项之一。找到的程序集的清单定义与程序集引用不匹配。 (HRESULT 异常:0x80131040)

这是我使用它的类:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(CorsOptions.AllowAll); //HERE IS THE PROBLEM
        HttpConfiguration configuration = new HttpConfiguration();
        configuration.Routes.MapHttpRoute(
            name: "TestApi",
            routeTemplate: "test/{controller}/{id}",
            defaults: new {id = RouteParameter.Optional}
        );
        app.UseWebApi(configuration);
    }
}

我调试了,我的问题是当我使用app.UserCors(CorsOptions.AllowAll) 函数时。我使用 Nuget 包管理器安装了 Microsoft CORS 包,并尝试对其进行更新,但仍然出现此错误。我在这里搜索了Can't load System.Web.Cors assembly after call to Microsoft.Owin.Cors,但该解决方案对我不起作用。

我有这个 app.config 文件:

  <runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="2.0.2.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="3.0.1" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
</assemblyBinding>

也许问题出在 System.Web.Cors 中?我有点迷茫。

【问题讨论】:

    标签: c# .net asp.net-web-api .net-assembly


    【解决方案1】:

    在你的配置中你说

    <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="2.0.2.0" />
      </dependentAssembly>
    

    这意味着,您使用 Microsoft.Owin 版本 2.0.2.0 但是您的一些代码(我想是 IAppBuilder 的实现)需要“Microsoft.Owin,Version=3.0.1.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35”

    如果你使用 NuGet,升级包,如果没有 - 你应该下载 3.0.1.0 版本,更新参考和更改配置文件

    【讨论】:

    • 谢谢这解决了我的问题。我不知道为什么使用 nuget 包管理器会弄乱我的 app.config 文件。我尝试通过命令行安装 owin,现在该部分编写得很好并且可以正常工作。
    最近更新 更多