CORS适用于对API的直接请求,但不适用于静态文件(如CSS) [英] CORS works for direct requests to API but not for static files (like css)

查看:127
本文介绍了CORS适用于对API的直接请求,但不适用于静态文件(如CSS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发一个由Android Mobile AppWeb API组成的项目. Web API是Asp.net MVC Core.

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.

我已经在Startup.cs上启用了CORS服务,因此移动应用程序API调用可以跨源访问,并且我在响应标头中收到access-control-allow-origin →*.

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.

API返回到移动应用程序请求的一部分结果是HTML(将在移动视图中显示为广告),其中包含一些CSS文件.在Mobile View中加载HTML时,CSS文件不会加载,因为它们似乎无法跨源访问.

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?

我的CORS配置如下:

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 => .... );
    ...
}

推荐答案

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

尝试我完整的示例 https://github.com/DureSameen/CorsStaticFiles

这篇关于CORS适用于对API的直接请求,但不适用于静态文件(如CSS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆