Soufian Chaoui
Soufian Chaoui

Reputation: 47

Allowing same origin for static files .Net Core

Why i try to access a static file in my dot net core backend i get

Access to XMLHttpRequest at 'https://localhost:5001/uploads/132248599151771104.jpg' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

And this message in the .net console

CORS policy execution successful.

i've tried

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

and

   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 ();
    });
}

Upvotes: 1

Views: 1613

Answers (1)

Bob Ash
Bob Ash

Reputation: 887

You need to put app.UseCors ("CorsPolicy"); as the first line in Configure method.

Upvotes: 1

Related Questions