如何在Web API2中使用CORS禁用特定域?

时间:2015-08-06 06:01:18

标签: asp.net-web-api asp.net-web-api2

我使用" System.Web.Http.Cors"启用了CORS。并希望阻止某些域名。我想让这个动态,即拥有权限的域名将从我从Azure管理的APP SETTINGS中挑选出来。为此,我实施了" ICorsPolicyProvider"以下方式:

public class EnableCorsAttribute: Attribute, ICorsPolicyProvider
{
    private CorsPolicy _policy;

    public EnableCorsAttribute(string appSettingOriginKey)
    {
        _policy = new CorsPolicy
        {
            AllowAnyMethod = true,
            AllowAnyHeader = true
        };

        // loads the origins from AppSettings
        string originsString = CloudConfigurationManager.GetSetting(appSettingOriginKey);
        if (!String.IsNullOrEmpty(originsString))
        {
            foreach (var origin in originsString.Split(','))
            {
                _policy.Origins.Add(origin);
            }
        }
    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(_policy);
    }
}

但它仍允许所有域名。有什么想法或建议吗?

0 个答案:

没有答案