c# - WebAPI - 为子域启用 CORS

标签 c# asp.net-web-api cors

我想为具有以下条件的 web-api 应用程序启用 CORS:

  1. 允许同一站点使用 HTTPS 或 HTTP
  2. 忽略 SUBDOMAIN - 表示 mysite.comwww.mysite.com 相同

我想以优雅的方式为多个站点执行此操作,而不是将所有排列都用逗号分隔。

提前致谢!

最佳答案

给你。

添加 Git gist如果它需要任何修改或错误修复。

public class WildcardOriginCorsPolicy : Attribute, ICorsPolicyProvider
    {
        private readonly string _origins;
        private readonly string _headers;
        private readonly string _methods;

        //private readonly CorsPolicy _policy;
        //
        // Summary:
        //     Initializes a new instance of the WildcardOriginCorsPolicy class.
        //
        // Parameters:
        //   origins:
        //     Comma-separated list of origins that are allowed to access the resource. Use
        //     "*" to allow all.
        //     "*.example.com" for subdomains
        //
        //   headers:
        //     Comma-separated list of headers that are supported by the resource. Use "*" to
        //     allow all. Use null or empty string to allow none.
        //
        //   methods:
        //     Comma-separated list of methods that are supported by the resource. Use "*" to
        //     allow all. Use null or empty string to allow none.
        public WildcardOriginCorsPolicy(string origins, string headers, string methods)
        {
            this._origins = origins;
            this._headers = headers;
            this._methods = methods;
        }

        public bool SupportsCredentials { get; set; }

        public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var policy = CreatePolicy(request.GetCorsRequestContext(), this._origins, this._headers, this._methods);
            policy.SupportsCredentials = this.SupportsCredentials;

            return Task.FromResult(policy);
        }

        private static CorsPolicy CreatePolicy(CorsRequestContext requestContext, string origins, string headers, string methods)
        {

            var corsPolicy = new CorsPolicy();
            if (origins == "*")
            {
                corsPolicy.AllowAnyOrigin = true;
            }
            else
            {
                var originsStringArray = origins.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var requestOrigin = requestContext.Origin.ToLowerInvariant();

                foreach (var originItem in originsStringArray)
                {
                    ////Check if the current request uri matches with any of the wildcard origins.
                    if (Regex.IsMatch(requestOrigin, WildCardToRegularExpression(originItem)))
                    {
                        corsPolicy.Origins.Add(requestOrigin);
                    }
                }
            }

            if (!String.IsNullOrEmpty(headers))
            {
                if (headers == "*")
                {
                    corsPolicy.AllowAnyHeader = true;
                }
                else
                {
                    var headersStringArray = headers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    corsPolicy.Headers.AddAll(headersStringArray);
                }
            }

            if (!String.IsNullOrEmpty(methods))
            {
                if (methods == "*")
                {
                    corsPolicy.AllowAnyMethod = true;
                }
                else
                {
                    var methodsStringArray = methods.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    corsPolicy.Methods.AddAll(methodsStringArray);
                }
            }

            return corsPolicy;
        }

        private static string WildCardToRegularExpression(String value)
        {
            return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
        }
    }

像这样使用它。

var cors = new WildcardOriginCorsPolicy("*.example.com,http://localhost:*", "*", "POST,PUT,DELETE,GET,OPTIONS") { SupportsCredentials = true };
config.EnableCors(cors);

关于c# - WebAPI - 为子域启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36307907/

相关文章:

c# - Visiblox LabelsContainer 调整?

javascript - 如何设置公共(public) Google Cloud Storage 存储桶的 CORS 以避免使用 javascript fetch 函数时出现错误?

gwt - CORS 和 GWT 现在可以使用吗?

c# - List<T> FirstOrDefault() 性能不佳 - 在这种情况下可以使用字典吗?

c# - 使用 Reporting Services 将组保持在一页上

c# - 使用 Docker 构建应用程序时打开控制台窗口

c# - 使用具有备用内容类型的 c# web api

c# - 将实时推文流式传输到 my .net 网站

asp.net-core - Swagger Swashbuckle 多态性不适用于接口(interface)类型

iis - 为什么 IIS CORS 模块 'Access-Control-Allow-Origin' 似乎被缓存了?