【问题标题】:Asp.NET MVC Core CORSAsp.NET MVC 核心 CORS
【发布时间】:2016-12-14 17:57:18
【问题描述】:

我们正在开发具有移动部分和 Web UI 的应用程序。 Web UI 使用 Angular,我们在后端配置 cors 时遇到问题。我们的代码如下所示(只是对我们的问题很重要的代码):

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors("AllowAll");

    app.UseMvc();
}

public void ConfigureServices(IServiceCollection services)
{            
    services.AddMvc();

    //Add Cors support to the service
    services.AddCors(
        options => options.AddPolicy(
            "AllowAll", p => p.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials()
            )
        );
}

从文档和stackoverflow 上的其他帖子来看,这应该可以,但不是。我们错过了什么?

thnx


编辑:

这是来自 POSTMAN 的请求:

curl 'https://guw.azurewebsites.net/api/token' -X OPTIONS -H '编译指示: 无缓存' -H '访问控制请求方法:POST' -H '来源: http://localhost:9000' -H '接受编码:gzip、deflate、sdch、br' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36' -H '接受:/' -H '缓存控制:无缓存' -H '引用者:http://localhost:9000/' -H '连接:保持活动' -H '访问控制请求标头:接受, 授权,内容类型'--压缩

您可以在邮递员中导入它并查看它。此请求由 Angular 应用发送。

希望这会有所帮助。

最后我决定在我的中间件中添加这个方法:

private void AddCors(HttpContext context)
{
    context.Response.Headers.Add("Access-Control-Allow-Headers", 
        new string[] { "Authorization", "Content-Type" });
    context.Response.Headers.Add("Access-Control-Allow-Methods", 
        new string[] { "OPTIONS", "POST", "GET", "DELETE", "PUT" });

    IEnumerable<string> allowedUrls = new List<string>()
    {
        "http://localhost:8100", 
        "http://localhost:9000"
    };

    if (allowedUrls.Count() > 0)
    {
        foreach(string x in allowedUrls)
        {
            var origin = context.Request.Headers.FirstOrDefault(
                key => key.Key == "Origin");
            var found = x.ToLower() == origin.Value.ToString().ToLower();
            if (found)
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", 
                    new string[] { origin.Value });
            }
        }
    }

    return;
}

编辑:

这很好,但在逻辑上它没有按我的需要工作,所以我最终在我的中间件类中使用了这个,而且效果很好:

// Add CORS to every response
context.Response.Headers.Add("Access-Control-Allow-Headers", 
    new string[] { "Authorization", "Content-Type" });
context.Response.Headers.Add("Access-Control-Allow-Methods", 
    new string[] { "OPTIONS", "POST", "GET", "DELETE", "PUT" });
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

if (context.Request.Method.Equals("OPTIONS", StringComparison.Ordinal))
{ 
    context.Response.StatusCode = 204;
    return _next(context);
}

谢谢

【问题讨论】:

  • “这应该可以,但不行”您需要edit添加有关您如何测试它以及为什么它“但不行”的详细信息
  • 我最后在中间件中添加了我的方法。编辑了我的帖子。
  • @Wasyster Vow,为什么要添加这么多代码? MVC 不是已经为你做这件事了吗?
  • 信不信由你,它没有做,我包括了一切。尝试了每种组合来弄清楚,但从未奏效。
  • 为了搜索者的利益,我在 CORS 上遇到了类似的问题 - 在此处发布了我的答案 -> stackoverflow.com/a/40286658/852806

标签: asp.net-core cors asp.net-core-mvc


【解决方案1】:

在我的应用程序(以 angular2 作为前端)中,我按照以下方式进行操作-

        app.UseCors(builder => {
            builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        });

请参阅此以获取更多信息 - https://docs.asp.net/en/latest/security/cors.html

看看这是否有帮助。

【讨论】:

  • 这正是我的 Angular2 应用程序所需要的,链接是帮助解释为什么这些额外的方法是“正常工作”的肉汁。 +1
【解决方案2】:

您应该阅读以下文章以更好地了解如何在 ASP.NET 5 中使用 Cors。

https://docs.asp.net/en/latest/security/cors.html

基本上UseCors注册了一个Cors中间件来处理Cors相关的请求。但是您实际上不需要在您的情况下注册它,因为 MVC 具有以类似方式处理它的内置组件(过滤器)。 Cors 中间件在您不想使用 MVC 的情况下很有用。

因此,对于您的场景,请删除 UseCors 注册,如果您查看上面的链接,您会看到要启用全局 Cors 策略,您可以执行以下操作:

services.Configure<MvcOptions>(options =>
{
    options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
});

【讨论】:

  • 在这种情况下,您需要提供更多信息。请求如何通过网络发送,您尝试执行的操作等。
猜你喜欢
  • 2020-12-06
  • 2021-12-31
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 2017-08-25
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多