配置 cors 以允许所有使用 ASP.NET Core 的子域(Asp.net 5、MVC6、VNext) [英] Configure cors to allow all subdomains using ASP.NET Core (Asp.net 5, MVC6, VNext)

查看:65
本文介绍了配置 cors 以允许所有使用 ASP.NET Core 的子域(Asp.net 5、MVC6、VNext)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.NET Core Web 应用程序中正确设置了 cors.我使用以下包...

I have cors setup correctly in an ASP.NET Core web app. Im using the following package...

"Microsoft.AspNet.Cors": "6.0.0-rc1-final"

这里是 startup.cs 片段...

and here is the startup.cs snippet...

public virtual IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddCors
    (
        options =>
        {
            options.AddPolicy
            (
                CORSDefaults.PolicyName, 
                builder =>
                {
                    //From config...
                    var allowedDomains = new []{"http://aaa.somewhere.com","https://aaa.somewhere.com","http://bbb.somewhere.com","https://bbb.somewhere.com"};

                    //Load it
                    builder
                        .WithOrigins(allowedDomains)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                }
            );
        }
    );
}

这很好用,只是允许的子域列表增长很快,我想允许somewhere.com"的所有子域.诸如*.somewhere.com"之类的东西.我似乎无法在新的 ASP.NET Core(MVC6、ASP.NET5、VNext)中找到有关如何执行此操作的任何文档.我发现的所有演示如何执行此操作的文档/示例都适用于早期版本的 MVC 或 WebApi.如何在新堆栈中实现这一点?

This works great except that the list of subdomains to allow is growing fast and I want to allow all subdomains of "somewhere.com". Something like "*.somewhere.com". I cant seem to find any documentation on how to do this in the new ASP.NET Core (MVC6, ASP.NET5, VNext). All the docs/examples I'm finding that demonstrate how to do this are for earlier versions of MVC or WebApi. How can I achieve this in the new stack?

推荐答案

此功能现已在 2.0.0 版中实现.在您的 ConfigureServices 中使用以下内容:

This has now been implemented in version 2.0.0. In your ConfigureServices use the following:

options.AddPolicy("MyCorsPolicy",
   builder => builder
      .SetIsOriginAllowedToAllowWildcardSubdomains()
      .WithOrigins("https://*.mydomain.com")
      .AllowAnyMethod()
      .AllowCredentials()
      .AllowAnyHeader()
      .Build()
   );

此外,不要忘记在您的 Configure 调用中也调用 UseCors:

Also, don't forget to call UseCors in your Configure call too:

app.UseCors("MyCorsPolicy");

这篇关于配置 cors 以允许所有使用 ASP.NET Core 的子域(Asp.net 5、MVC6、VNext)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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