繁体   English   中英

发布启用了CORS的网站

[英]Publish web site with CORS enabled

我是第一次参与网站的部署。 我正在从客户端上的Angular控制器在Web api控制器中进行跨源请求(CORS)。 为了进行开发,我已经在Web Api控制器上设置了EnableCors属性,但是显然,它指向本地计算机上的站点。 我试图弄清楚如何在将其移至托管生产站点时轻松转换该设置。

为所有域启用CORS

您的第一个选择是为所有域启用CORS。 例如,如果您知道只能从一组预定义的网站(例如,Angular应用程序)访问您的API,这可能不是最安全的选择。 但是在某些情况下,可以全局启用CORS。

您可以从WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable CORS globally for all routes
        var enableCorsAttribute = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(enableCorsAttribute);

        // Other configurations
    }
}

或在配置中启用CORS支持,然后在特定的控制器/操作上使用EnableCors属性:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        // Other configurations
    }
}

public class ValuesController : ApiController
{    
    [HttpGet]
    [Route("api/values")]
    [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
    public string[] GetValue()
    {

    }
}

从Azure门户启用CORS

如果托管在Azure中,我认为Web Apps现在允许您启用CORS支持并直接从Azure门户指定允许的域:

在此处输入图片说明

根据应用设置启用CORS

另一个选项是为可通过“应用程序设置”配置的域启用CORS。 这样,您可以使用web.config转换,部署令牌注入或仅使用Azure应用设置来更改不同API实例的允许域。 这可以通过创建自己的实现ICorsPolicyProvider接口的属性来轻松实现:

// The implementation below supports only a single origin and
// doesn't allow you to specify allowed headers or request types.
// But it can be easily extended to support these scenarios as well.
public class EnableCorsWithConfigAttribute : Attribute, ICorsPolicyProvider
{
    private readonly string configKey;

    public EnableCorsWithConfigAttribute(string configKey)
    {
        this.configKey = configKey;
    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, 
                                               CancellationToken cancellationToken)
    {
        var policy = new CorsPolicy
        {
            AllowAnyOrigin = false,
            AllowAnyHeader = true,
            AllowAnyMethod = true,
        };

        if (ConfigurationManager.AppSettings
                                .AllKeys
                                .Contains(configKey))
        {
            var origin = ConfigurationManager.AppSettings[configKey];
            if (!origins.IsNullOrWhitespace())
            {
                policy.AllowAnyOrigin = origins.Equals("*");
                if (!policy.AllowAnyOrigin) policy.Origins.Add(origin);
            }
        }

        return Task.FromResult(policy);
    }
}

然后,您可以按以下方式使用它:

public class ValuesController : ApiController
{    
    [HttpGet]
    [Route("api/values")]
    [EnableCorsWithConfig("Application:Cors:AllowedOrigin")]
    public string[] GetValue()
    {

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM