2016-11-03 2 views
3

Ich habe ein ASP .NET Core selbst gehostetes Projekt. Ich liefere Inhalte aus einem statischen Ordner (kein Problem). Es liefert Images ohne Probleme quer durch die Site (CORS-Header erscheint). Bei einigen Dateitypen wie JSON werden die CORS-Header jedoch nicht angezeigt, und die Clientwebsite kann den Inhalt nicht sehen. Wenn ich die Datei in einen unbekannten Typ umbenenne (zB JSONX), wird sie mit CORS-Headern geliefert, kein Problem. Wie kann ich dieses Ding bekommen, um alles mit einem CORS-Header zu bedienen?ASP.NET Core: CORS-Header nur für bestimmte statische Dateitypen

Ich habe folgende CORS Politik in meinem Startup.cs einzurichten:

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

     // Add framework services. 
     services.AddMvc(); 
    } 

Und die folgenden ist mein Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     app.UseCors("CorsPolicy"); 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
      app.UseBrowserLink(); 
     } 
     else 
     { 
      app.UseExceptionHandler("/Home/Error"); 
     } 

     // Static File options, normally would be in-line, but the SFO's file provider is not available at instantiation time 
     var sfo = new StaticFileOptions() { ServeUnknownFileTypes = true, DefaultContentType = "application/octet-stream", RequestPath = "/assets"}; 
     sfo.FileProvider = new PhysicalFileProvider(Program.minervaConfig["ContentPath"]); 
     app.UseStaticFiles(sfo); 

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

Was passiert, wenn Sie 'app.UseCors (" CorsPolicy ")' * nach * den Aufruf von 'app.UseStaticFiles (sfo)' aufrufen? – haim770

+0

Ich habe es gerade getestet: Wenn CORS danach kommt, dann bekommt keine der statischen Dateien den CORS-Header. – Blake

Antwort

0

Middleware kann mit dieser Art von komplexer Logik helfen. Ich habe dies kürzlich für JavaScript-Quellen arbeiten lassen. Es sieht so aus, als wäre der Medientyp für JSON "application/json".

/* 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Http; 

Made available under the Apache 2.0 license. 
https://www.apache.org/licenses/LICENSE-2.0 
*/ 

/// <summary> 
/// Sets response headers for static files having certain media types. 
/// In Startup.Configure, enable before UseStaticFiles with 
/// app.UseMiddleware<CorsResponseHeaderMiddleware>(); 
/// </summary> 
public class CorsResponseHeaderMiddleware 
{ 
    private readonly RequestDelegate _next; 

    // Must NOT have trailing slash 
    private readonly string AllowedOrigin = "http://server:port"; 


    private bool IsCorsOkContentType(string fieldValue) 
    { 
     var fieldValueLower = fieldValue.ToLower(); 

     // Add other media types here. 
     return (fieldValueLower.StartsWith("application/javascript")); 
    } 


    public CorsResponseHeaderMiddleware(RequestDelegate next) { 
     _next = next; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     context.Response.OnStarting(ignored => 
     { 
      if (context.Response.StatusCode < 400 && 
       IsCorsOkContentType(context.Response.ContentType)) 
      { 
       context.Response.Headers.Add("Access-Control-Allow-Origin", AllowedOrigin); 
      } 

      return Task.FromResult(0); 
     }, null); 

     await _next(context); 
    } 
} 
Verwandte Themen