Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS works for direct requests to API but not for static files (like css)

We are developing a project which is consisted of an Android Mobile App along with a Web API. The web API is Asp.net MVC Core.

I have enabled the CORS service on my Startup.cs, hence Mobile app API calls are Cross Origin accessible and I receive access-control-allow-origin →* in the response headers.

A part of the result that API returns to the mobile app request is HTML (to be shown as an ad in a mobile view) containing some CSS files. When the HTML is loaded in the Mobile View, CSS files do not load because they seem not to be Cross Origin accessible.

Is there something I'm missing? Have I missed any configuration steps?


my CORS configuration is as follows:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddCors(options =>
    {
        options.AddPolicy("RTBCors",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            //.AllowCredentials()
            );
    });
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new Microsoft.AspNetCore.Mvc.Cors.Internal.CorsAuthorizationFilterFactory("RTBCors"));
    });
    services.AddMvc(...);
    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...
    app.UseCors("RTBCors");
    app.UseMvc(routes => .... );
    ...
}
like image 549
Mahdi Tahsildari Avatar asked Oct 29 '22 03:10

Mahdi Tahsildari


1 Answers

app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    if (context.File.Name.ToLower().EndsWith(".json"))
                    {
                        var origin = context.Context.Request.Headers[CorsConstants.Origin];
                        var requestHeaders = context.Context.Request.Headers;

                        var isOptionsRequest = string.Equals(context.Context.Request.Method, CorsConstants.PreflightHttpMethod, StringComparison.OrdinalIgnoreCase);
                        var isPreflightRequest = isOptionsRequest && requestHeaders.ContainsKey(CorsConstants.AccessControlRequestMethod);

                        var corsResult = new CorsResult
                        {
                            IsPreflightRequest = isPreflightRequest,
                            IsOriginAllowed = IsOriginAllowed(Policy, origin),
                        };

                   if (!corsResult.IsOriginAllowed)
                        { context.Context.Response.StatusCode = 204;
                           }
                    }

Try my complete sample https://github.com/DureSameen/CorsStaticFiles

like image 113
Dure Sameen Avatar answered Nov 15 '22 05:11

Dure Sameen