.NET Core中的CORS

我试图以这种方式在.NET Core中启用CORS:

public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader())); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseCors("AllowAll"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } 

但是,当我通过Angular 2向我的应用程序发送请求时,我得到了名人

“请求的资源上没有’Access-Control-Allow-Origin’标头。”

错误信息。

我也在使用Windows身份validation+ WebListener。 如果我与邮递员核对,唯一的响应标题是:

Content-Length→3533 Content-Type→application / json; charset = utf-8日期→2016年10月14日星期五12:17:57 GMT服务器→Microsoft-HTTPAPI / 2.0

所以仍然必须配置错误。 有什么建议?

如果我删除它已运行的outcommented行,但我需要Windows身份validation:-(

  var host = new WebHostBuilder() .UseWebListener() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup() //.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM) .Build(); 

假设您有答案,但为了搜索者的利益,我在.NET Core Cors的标准教程中遇到了同样的问题。

遇到的许多错误之一:

XMLHttpRequest无法加载localhost:64633 / api / blogs。 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许原点’localhost:56573’访问。 响应的HTTP状态代码为500。

玩完之后,以下代码有效。 全class发布在下面,以帮助理解什么在哪里。

 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Cors.Infrastructure; namespace NetCoreWebApiTesting { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsEnvironment("Development")) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: true); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); // ******************** // Setup CORS // ******************** var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); // For anyone access. //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end! corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); app.UseMvc(); // ******************** // USE CORS - might not be required. // ******************** app.UseCors("SiteCorsPolicy"); } } } 

要使用它,您可以在控制器或方法上添加EnableCorsAttribute 。 例如

 [EnableCors("SiteCorsPolicy")] [Route("api/[controller]")] public class BlogsController : Controller { } 

要么

 // POST api/value [EnableCors("SiteCorsPolicy")] [HttpPost] public HttpResponseMessage Post([FromBody]Blog value) { // Do something with the blog here.... var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK); return msg; } 

当我使用以下代码调用它时(使用标准的js / jQuery以便于复制和粘贴),通信停止被拒绝。

 function HandleClick() { var entityData = { "blogId": 2, "url": "http://blog.com/blog1", "posts": [ { "postId": 3, "title": "Post 1-1", "content": "This is post 1 for blog 1", "blogId": 2 }, { "postId": 4, "title": "Post 1-2", "content": "This is post 2 for blog 1", "blogId": 2 } ] }; $.ajax({ type: "POST", url: "http://localhost:64633/api/blogs", async: true, cache: false, crossDomain: true, data: JSON.stringify(entityData), contentType: "application/json; charset=utf-8", dataType: "json", success: function (responseData, textStatus, jqXHR) { var value = responseData; }, error: function (responseData, textStatus, errorThrown) { alert('POST failed.'); } }); } 

这种方式正常工作,只是在带有.net核心的angular2上尝试过。 OP所面临的问题是,这不适用于Windows身份validation。 我假设Windows身份validation的中间件正在发出请求之前发生,在这种情况下它会破坏。 最好的办法是看看在配置中处理cors中间件后是否有办法启用Windows auth中间件。

那顺序就是

App.UseCors()

App.UseWindowsAuth()

App.UseMVC()

它们必须按此顺序发生才能发挥作用。

 public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader())); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseCors("AllowAll"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } 

文档遗漏的是.AllowAnyMethod()的重要性。 如果不存在,可怕的No’Access-Control-Allow-Origin’会让你烦恼。 在你的代码中它就在那里,所以我猜你错过了在jour客户端应用程序中设置正确的标题。

我个人通过允许所有人来完成工作:

 app.UseCors(b => b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials()); 

而我的Angularpost的function如下:

 post(model) { let headers = new Headers({ 'Content-Type':'application/json; charset=utf-8;' ,'Accept':'*/*' }); let options = new RequestOptions({ headers: headers }); let body = JSON.stringify(model); return this.http.post( 'http://localhost:58847/api/TestPost', body, options) .map((response: Response) => { let res = response.json(); return res; } ); } 

之后,您可以通过指定原点等逐步完成工作。

在ASPNET CORE 2.0中,以下内容适用于我

  public void ConfigureServices(IServiceCollection services) { services.Configure(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin")); }); services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("http://localhost:5000").AllowAnyHeader() .AllowAnyMethod()); }); services.AddMvc() } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { loggerFactory.AddConsole(); loggerFactory.AddDebug(LogLevel.Information); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Shows UseCors with named policy. app.UseCors("AllowSpecificOrigin"); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvcWithDefaultRoute(); } } 

@HockeyJ的答案是正确的,但如果需要,你可以做一些更简洁的事情。

 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //Or if you want to chose what to include services.AddMvcCore() .AddCors() (...) } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //Cors app.UseCors(builder => { builder.AllowAnyHeader(); builder.AllowAnyMethod(); builder.AllowCredentials(); builder.AllowAnyOrigin(); // For anyone access. //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. }); }