【问题标题】:Allowing same origin for static files .Net Core允许静态文件同源.Net Core
【发布时间】:2020-01-30 14:36:01
【问题描述】:

为什么我尝试在我的 dot net core 后端访问静态文件

从源“http://localhost:4200”访问“https://localhost:5001/uploads/132248599151771104.jpg”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

.net 控制台中的这条消息

CORS 策略执行成功。

我试过了

            services.AddCors (options => {
                options.AddPolicy ("CorsPolicy", builder => {
                    builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod ()
                        .AllowAnyOrigin()
                        .AllowAnyHeader ();
                });
            });

   app.UseStaticFiles ();
            app.UseStaticFiles (new StaticFileOptions {
                 OnPrepareResponse = ctx => {
                    ctx.Context.Response.Headers.Append(new KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>("Access-Control-Allow-Origin", "*"));
                    ctx.Context.Response.Headers.Append(new KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"));


                },

                FileProvider = new PhysicalFileProvider (
                        Path.Combine (Directory.GetCurrentDirectory (), "Uploads")),
                    RequestPath = new Microsoft.AspNetCore.Http.PathString ("/Uploads")
            });

Startup.cs:

public void ConfigureServices (IServiceCollection services) {
    services.AddMvc ().SetCompatibilityVersion (CompatibilityVersion.Version_2_2);

    var key = Encoding.ASCII.GetBytes ("this is the secret phrase");

    services.AddAuthentication (x => {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer (x => {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey (key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

    //Enable Cross-Origin Resource Sharing (Front-end and backend on the same server)
    services.AddCors (options => {
        options.AddPolicy ("CorsPolicy", builder => {
            builder
                .AllowAnyOrigin()
                .AllowAnyMethod ()
                .AllowAnyOrigin()
                .AllowAnyHeader ();
        });
    });
    services.AddControllers ().AddNewtonsoftJson (options => {
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

    // 
    services.AddDbContext<DataBaseContext> (options => {
        options.UseSqlServer (Configuration.GetConnectionString ("db0"));
    });
    services.AddControllers ();

    services.AddDbContext<RailOpsContext> (options =>
        options.UseSqlServer (Configuration.GetConnectionString ("RailOpsContext")));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure (IApplicationBuilder app, IWebHostEnvironment env) {
    app.UseDefaultFiles ();
    app.UseStaticFiles ();
    app.UseStaticFiles (new StaticFileOptions {
            OnPrepareResponse = ctx => {
            ctx.Context.Response.Headers.Append(new KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>("Access-Control-Allow-Origin", "*"));
            ctx.Context.Response.Headers.Append(new KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"));


        },

        FileProvider = new PhysicalFileProvider (
                Path.Combine (Directory.GetCurrentDirectory (), "Uploads")),
            RequestPath = new Microsoft.AspNetCore.Http.PathString ("/Uploads")
    });

    // app.UseDirectoryBrowser (new DirectoryBrowserOptions () {
    //     FileProvider = new PhysicalFileProvider (
    //             Path.Combine (Directory.GetCurrentDirectory (), @"Uploads")),
    //         RequestPath = new Microsoft.AspNetCore.Http.PathString ("/Uploads")
    // });

    app.UseCors ("CorsPolicy");
    if (env.IsDevelopment ()) {
        app.UseDeveloperExceptionPage ();
    }

    app.UseHttpsRedirection ();

    app.UseRouting ();

    app.UseAuthentication ();
    app.UseAuthorization ();

    app.UseEndpoints (endpoints => {
        endpoints.MapControllers ();
    });
}

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    你需要把 app.UseCors("CorsPolicy");作为 Configure 方法的第一行。

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2021-09-29
      • 2020-01-31
      • 2018-07-05
      • 2019-07-29
      相关资源
      最近更新 更多