2017-08-18 26 views
1

即使请求被视为CORS,即使它位于同一个域中的地址之间,但使用不同的协议?从http呼叫https时,Chrome抛出CORS错误,而ASP Core不发送CORS头

因为我在控制台中看到代码401:

XMLHttpRequest cannot load 
https://xxx.yyy.com/appname/css/left-pane-menu.component.min.css. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://xxx.yyy.com' is therefore not allowed access. 
The response had HTTP status code 401. 

一方面,asp的核心将不会发送CORS标头为同一来源,对其他Chrome不会接受来自其他协议的请求。哇。

除了从相同的协议调用资源,我的选择是什么。 我不能那样做。我需要调用https,总是因为某些Azure Enterprise代理设置导致我的网站误认为在使用https调用时使用http调用,因此html中的基本url标记设置为http://xxx.yyy.com/myapp,Chrome会抛出它无法访问不安全来自安全连接的资源。

我Startup.cs看起来是这样的:

public void ConfigureServices(IServiceCollection services) 
{ 
     services.AddCors(); 
     services.AddMvc() 
       .AddJsonOptions(x => 
       { 
        x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 
       }); 
} 


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
      app.UseCors(c=> 
       c 
       .AllowAnyOrigin() 
       .AllowAnyMethod() 
       .AllowAnyHeader() 
       .AllowCredentials() 
      ); 

     app.UseResponseCompression(); 

     app.UseStaticFiles(new StaticFileOptions()); 

     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}"); 
      routes.MapSpaFallbackRoute("spa-fallback", new { controller = "Home", action = "Index" }); 
     }); 
} 
+1

这是正确的行为。 Http/https被分类为不同的来源。您必须在您的申请中处理允许http和https都允许 – Tseng

+0

但您的Cors也配置错误。你应该把CORS放在你的静态文件中间件之后(或者只限于js/json),因为甚至css都会通过CORS检查,你很可能不想这样做。同时发布您的CORS设置代码 – Tseng

+1

您使用什么进行授权? –

回答

1

你需要设置你的CORS以类似的东西,因为https://xxx.yyy.comhttp://xxx.yyy.com作为不同来源对待。

背后的原因是,不同的端口也被归类为不同的起源和HTTP端口80上运行,并在HTTPS 443

有些浏览器不同的方式对待这一点,即Internet Explorer中没有(或者它使用的,不知道它是否仍然适用于新版本)将不同的端口视为相同的原始文件,Firefox和Chrome不会(根据规范,这是正确的行为)。

options.AddPolicy("YYYOrigin", policyBuilder => 
{ 
    policyBuilder 
     // you need to specify both 
     .WithOrigins("https://xxx.yyy.com", "http://xxx.yyy.com") 
     .AllowAnyMethod() 
     .AllowAnyHeader(); 
}); 

app.UseCors("YYYOrigin"); 
+0

但是如果我有。 AllowAnyOrigin()? – doker

+0

'.AllowAnyOrigin()'应该总是能够工作,除非你的代码抛出异常,因为异常中间件清除了所有头文件,包括CORS头文件如果加载的文件是AngularJS应用程序的一部分通过AJAX下载css文件),然后把UseCors(“...”)放在你的静态中间件之前,否则,如果你只想保护你的控制器rs/actions – Tseng

+0

您需要在授权之前注册您的静态中间件,否则您的应用无法加载未经授权的用户(第一次访问者) – Tseng