WebAPI-为子域启用CORS [英] WebAPI - Enable CORS for Subdomains

查看:57
本文介绍了WebAPI-为子域启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望启用具有以下条件的Web-api应用程序的CORS:

I would like to be enable CORS for a web-api application with the following criteria:

  1. 允许同一站点使用HTTPS或HTTP
  2. 忽略该子域-含义 mysite.com www.mysite.com 相同

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

I would like to do this for multiple sites in an elegant way, rather than putting all the permutations as comma delimited.

提前谢谢!

推荐答案

在这里.

添加Git 要点,如果需要进行任何修订或错误修复.

Adding Git gist if it requires any revisions or bug fixes.

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

这篇关于WebAPI-为子域启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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