简体   繁体   English

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

[英]How to enable CORS globally in my ASP.NET core WebApi project

I am trying to migrate my Web Api2 to ASP.NET core web api project. 我正在尝试将我的Web Api2迁移到ASP.NET核心web api项目。 In my project we are using EnableCors features. 在我的项目中,我们使用的是EnableCors功能。

I found this document on Microsoft site, which I am using as a reference - https://docs.asp.net/en/latest/security/cors.html 我在Microsoft网站上找到了这个文档,我将其用作参考 - https://docs.asp.net/en/latest/security/cors.html

As mentioned in 'Enabling CORS in MVC' section, I am trying to enable cors globally in ConfigureServices menthod like this - 正如“在MVC中启用CORS”一节中所述,我试图在这样的ConfigureServices menthod中全局启用cors -

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

However, I am getting this error which I couldn't understood- 但是,我收到了这个我无法理解的错误 -

The call is ambiguous between the following methods or properties: 'Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action)' and 'Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action)' 以下方法或属性之间的调用不明确:'Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Extensions.DependencyInjection.IServiceCollection,System.Action)'和'Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Extensions) .DependencyInjection.IServiceCollection,System.Action)'

Refer Error Screenshot here - ERROR scrrenshot 在这里参考错误截图 - 错误scrrenshot

Could anyone please let me know how do I enable CORS globally in my ASP.NET core WebApi project? 有谁能告诉我如何在我的ASP.NET核心WebApi项目中全局启用CORS?

Project.json: 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" ]
  }
}

You mixed up the dependencies. 你混淆了依赖关系。

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

is an very old version and results in your solution having loaded two different assemblies with the same namespace and types and compiler doesn't know which one to use. 是一个非常旧的版本,导致您的解决方案加载了两个具有相同名称空间和类型的不同程序集,编译器不知道使用哪个程序集。

Change it to 将其更改为

"Microsoft.AspNetCore.Cors": "1.0.0" “Microsoft.AspNetCore.Cors”:“1.0.0”

All Microsoft.AspNet.* packages are very old and shouldn't be used. 所有Microsoft.AspNet.*包都非常陈旧,不应使用。 They all got renamed to Microsoft.AspNetCore.* with RC2 他们都用RC2重命名为Microsoft.AspNetCore.*

Asp.Net Documentation Says: Asp.Net文档说:

To setup CORS for your application add the Microsoft.AspNetCore.Cors package to your project. 要为应用程序设置CORS,请将Microsoft.AspNetCore.Cors包添加到项目中。 Add the CORS services in Startup.cs: 在Startup.cs中添加CORS服务:

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

To enable CORS for your entire application add the CORS middleware to your request pipeline using the UseCors extension method. 要为整个应用程序启用CORS,请使用UseCors扩展方法将CORS中间件添加到请求管道。 Note that the CORS middleware must precede any defined endpoints in your app that you want to support cross-origin requests (ex. before any call to UseMvc ). 请注意,CORS中间件必须位于应用程序中要支持跨源请求的任何已定义端点之前(例如,在调用UseMvc之前)。

You can specify a cross-origin policy when adding the CORS middleware using the CorsPolicyBuilder class. 使用CorsPolicyBuilder类添加CORS中间件时,可以指定跨源策略。 call UseCors with a lambda: 使用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!");
     });
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM