如何在我的ASP.NET核心WebApi项目中全局启用CORS

时间:2016-08-05 16:31:11

标签: asp.net-core asp.net-core-1.0 asp.net-core-webapi

我正在尝试将我的Web Api2迁移到ASP.NET核心web api项目。在我的项目中,我们使用的是EnableCors功能。

我在Microsoft网站上找到了此文档,我将其用作参考 - https://docs.asp.net/en/latest/security/cors.html

如'在MVC中启用CORS'部分所述,我试图在ConfigureServices menthod中全局启用cors -

services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });

但是,我收到了这个我无法理解的错误 -

  

以下方法或属性之间的调用不明确:   “Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Extensions.DependencyInjection.IServiceCollection,   System.Action)'和   “Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Extensions.DependencyInjection.IServiceCollection,   System.Action)'

请参阅错误屏幕截图 - ERROR scrrenshot

有谁能告诉我如何在我的ASP.NET核心WebApi项目中全局启用CORS?

Project.json:

{
  "userSecretsId": "aspnet5-MVC6",
  "version": "1.4.0-*",
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "dependencies": {
    "Microsoft.ApplicationInsights.AspNetCore": "1.0.0",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Identity": "1.0.0",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.0",

    "Microsoft.AspNet.Cors": "6.0.0-rc1-final",

    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.EntityFrameworkCore": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.Extensions.Configuration.CommandLine": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.SecretManager.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dnxcore50"
      ],
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      }
    },
    "net461": {
      "dependencies": {
        "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": "1.0.0-preview2-final"
      }
    }
  },

  "publishOptions": {
    "exclude": [
      "**.user",
      "**.vspscc",
      "wwwroot",
      "node_modules"
    ]
  },

  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }
}

3 个答案:

答案 0 :(得分:1)

您混淆了依赖项。

  

“Microsoft.AspNet.Cors”:“6.0.0-rc1-final”

是一个非常旧的版本,导致您的解决方案加载了两个具有相同名称空间和类型的不同程序集,编译器不知道使用哪个程序集。

将其更改为

  

“Microsoft.AspNetCore.Cors”:“1.0.0”

所有Microsoft.AspNet.*个包都很旧,不应该使用。他们都用RC2重命名为Microsoft.AspNetCore.*

答案 1 :(得分:0)

Asp.Net文档说:

要为您的应用程序设置CORS,请将Microsoft.AspNetCore.Cors包添加到您的项目中。 在Startup.cs中添加CORS服务:

public void ConfigureServices(IServiceCollection services)
{
      services.AddCors();
}

要为整个应用程序启用CORS,请使用UseCors将CORS中间件添加到请求管道中 扩展方法。请注意,CORS中间件必须位于应用程序中要支持跨源请求的任何已定义端点之前(例如,在调用UseMvc之前)。

使用CorsPolicyBuilder类添加CORS中间件时,可以指定跨源策略。使用lambda调用UseCors:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
     loggerFactory.AddConsole();
     if (env.IsDevelopment())
     {
        app.UseDeveloperExceptionPage();
     }
     // Shows UseCors with CorsPolicyBuilder.
     app.UseCors(builder =>
     builder.WithOrigins("http://example.com").AllowAnyMethod().AllowAnyHeader());
     app.Run(async (context) =>
     {
          await context.Response.WriteAsync("Hello World!");
     });
 }

答案 2 :(得分:0)

您可以在ConfigureServices()方法的“启动”类中配置CORS:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
    });
}

将其应用于每个请求或全局:

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");
}