WebAPI CORS 和 Ninject

Posted

技术标签:

【中文标题】WebAPI CORS 和 Ninject【英文标题】:WebAPI CORS and Ninject 【发布时间】:2013-09-24 01:12:35 【问题描述】:

我有一个带有 ninject 的 c# WebAPI 项目,并且所有的 get 函数都在工作。 但是,每次我尝试发布时,我都会从 api 获得“不允许的方法”响应。

我已经阅读了一些地方,当 api 拒绝跨源调用时,这是原因。

所以我使用包管理器控制台并安装了 Microsoft.AspNet.WebApi.Cors nugent 软件包并按照文章http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api 中的说明进行操作。

我现在的问题是 Ninject 不工作但抛出以下内容: 尝试通过方法 'System.Web.Http.GlobalConfiguration..cctor()' 访问字段 'System.Web.Http.GlobalConfiguration.CS$9__CachedAnonymousMethodDelegate2' 失败。"

有人可以帮我吗?

引发错误的行是: System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

Ninject 配置文件

public static class NinjectWebCommon

    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    
        bootstrapper.ShutDown();
    

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);

        System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

        return kernel;
    

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    
        kernel.Bind<MyCompany.Services.Domain.Repositories.IWorkRepository>().To<MyCompany.Services.Domain.Repositories.WorkRepository>();
        kernel.Bind<MyCompany.Services.Domain.Services.IAuthenticationService>().To<MyCompany.Services.Domain.Services.AuthenticationService>();
        kernel.Bind<MyCompany.Services.Domain.Utilties.IServiceFactory>().To<MyCompany.Services.Domain.Utilties.ServiceFactory>();
    

网页配置文件

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <!-- 
        Application Settings 
    -->
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusivejavascriptEnabled" value="true" />
  </appSettings>
  <!-- 
        Connection Strings 
    -->
  <connectionStrings>
    <!-- EDITED : Removed -->
  </connectionStrings>
  <!-- 
        System Web 
    -->
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="None" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <!-- 
        System Web Server
    -->
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
    </handlers>
    <httpProtocol>
      <customHeaders>
        <!-- Adding the following custom HttpHeader will help prevent CORS from stopping the Request-->
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
  <!-- 
        Runtime
    -->
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>

【问题讨论】:

您能否告诉我们此问题是否已解决或您是否仍有问题?是否可以共享独立的复制品?我目前正在尝试构建一个复制品,但如果您能提供一个,那将非常有帮助。 我得到了确切的错误。我正在使用 MVC5、CORS、StructureMap,我不认为这与依赖注入框架未能创建一些依赖关系有关,但可能是 CORS 的配置方式有问题,你找到解决方案了吗。跨度> 【参考方案1】:

您必须记住将您的 Microsoft.AspNet.WebApi 添加或更新到 RC 版本: http://www.nuget.org/packages/Microsoft.AspNet.WebApi

在包管理器控制台中:

PM> Install-Package Microsoft.AspNet.WebApi -Pre

PM> Install-Package Microsoft.AspNet.WebApi.Client -Pre

PM> Install-Package Microsoft.AspNet.WebApi.Core -Pre

【讨论】:

当我尝试第一次安装时,我得到:将“Microsoft.AspNet.WebApi 4.0.30506.0”更新为“Microsoft.AspNet.WebApi 5.0.0-rc1”失败。找不到与“Microsoft.AspNet.WebApi 5.0.0-rc1”兼容的“AspNetWebApi”版本。这可能是问题吗? @StephenCossgrove:看起来您尝试使用安装了package id="AspNetWebApi" version="4.0.20710.0" 的“Ninject.Web.WebApi”包...您需要从您的packages.config 中删除它,然后您可以尝试升级在此之后打包,它应该会成功

以上是关于WebAPI CORS 和 Ninject的主要内容,如果未能解决你的问题,请参考以下文章

WebAPI CORS 和静态文件

WebAPI 和令牌的可怕 CORS 问题

在 WebAPI 上启用 CORS,Chrome 和 FF 仍然不起作用

WebApi使用cors配置跨域问题

WebAPI CORS 和 Ninject

WebAPI - 为子域启用 CORS