问题 
我试图在我的 ASP.NET Core Web API 上启用跨域资源共享,但我卡住了。 
 
EnableCors 属性接受类型为 policyName 的字符串作为参数: 
- // Summary:
 
 - //     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
 
 - //
 
 - // Parameters:
 
 - //   policyName:
 
 - //     The name of the policy to be applied.
 
 - public EnableCorsAttribute(string policyName);
 
  复制代码 
政策名称是什么意思?如何在 ASP.NET Core Web API 上配置 CORS? 
 
回答 
CORS 策略必须在应用程序启动时在 ConfigureServices 方法中配置: 
- public void ConfigureServices(IServiceCollection services)
 
 - {
 
 -     services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
 
 -     {
 
 -         builder.AllowAnyOrigin()
 
 -                .AllowAnyMethod()
 
 -                .AllowAnyHeader();
 
 -     }));
 
  
-     // ...
 
 - }
 
  复制代码 
CorsPolicyBuilder 中的构建器允许您根据需要配置策略。该策略现在可以使用此名称应用于控制器和操作: 
 
[EnableCors("MyPolicy")] 
 
或将其应用于每个请求: 
- public void Configure(IApplicationBuilder app)
 
 - {
 
 -     app.UseCors("MyPolicy");
 
  
-     // ...
 
  
-     // This should always be called last to ensure that
 
 -     // middleware is registered in the correct order.
 
 -     app.UseMvc();
 
 - }
 
  复制代码 
 
 
 
 |