2016-11-03 4 views
3

私はASP .NETコアの自己ホストプロジェクトを持っています。私は静的フォルダからコンテンツを提供しています(問題ありません)。それは、問題なくクロスサイト画像を提供する(CORSヘッダが現れる)。ただし、JSONなどの一部のファイルタイプでは、CORSヘッダーが表示されず、クライアントサイトではコンテンツが表示されません。ファイルの名前をJSONXなどの不明なタイプに変更すると、CORSヘッダーで問題なく処理されます。 CORSヘッダーですべてを提供するにはどうしたらいいですか?ASP .NETコア:特定の静的ファイルタイプのCORSヘッダー

私はStartup.csに設定し、次のCORSポリシーがあります。

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

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

をそして次は私の設定

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

'app.UseStaticFiles(sfo)'の呼び出し後に 'app.UseCors(" CorsPolicy ")' *を呼び出した場合はどうなりますか? – haim770

+0

私はちょうどそれをテストしました:CORSが後に来るならば、静的なファイルのどれもがCORSヘッダーを取得しません。 – Blake

答えて

0

ミドルウェアは、複雑なロジックのこの種のを支援することができます。私は最近これをJavaScriptソース用に動作させています。 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); 
    } 
} 
関連する問題