简体   繁体   English

发布启用了CORS的网站

[英]Publish web site with CORS enabled

I'm diving into the deployment of websites for the first time. 我是第一次参与网站的部署。 I'm making Cross Origin Request (CORS) in the web api controller from an Angular controller on the client. 我正在从客户端上的Angular控制器在Web api控制器中进行跨源请求(CORS)。 For development, I've set the EnableCors attribute on the Web Api controller, but obviously, that's pointing to a site on my local machine. 为了进行开发,我已经在Web Api控制器上设置了EnableCors属性,但是显然,它指向本地计算机上的站点。 I'm trying to figure out how to easily transform that setting as I move it to a hosted production site. 我试图弄清楚如何在将其移至托管生产站点时轻松转换该设置。

Enable CORS For All Domains 为所有域启用CORS

You first option is to enable CORS for all domains. 您的第一个选择是为所有域启用CORS。 This might not be the most secure option if, for example, you know that your API will be accessed only from a pre-defined set of web sites (eg your Angular app). 例如,如果您知道只能从一组预定义的网站(例如,Angular应用程序)访问您的API,这可能不是最安全的选择。 But it some cases it is OK to enable CORS globally. 但是在某些情况下,可以全局启用CORS。

You can do it from WebApiConfig : 您可以从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
    }
}

Or enable CORS support in config and then use EnableCors attribute on specific controllers/actions: 或在配置中启用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()
    {

    }
}

Enable CORS From Azure Portal 从Azure门户启用CORS

If host in Azure, I think Web Apps now allow you to enable CORS support and to specify allowed domains right from the Azure Portal: 如果托管在Azure中,我认为Web Apps现在允许您启用CORS支持并直接从Azure门户指定允许的域:

在此处输入图片说明

Enable CORS Based on App Settings 根据应用设置启用CORS

Another option is to enable CORS for domains that can be configured from App Settings. 另一个选项是为可通过“应用程序设置”配置的域启用CORS。 This way you can change allowed domains for different API instances using web.config transforms, deployment token injection, or just Azure App Settings. 这样,您可以使用web.config转换,部署令牌注入或仅使用Azure应用设置来更改不同API实例的允许域。 This can be easily achieved by creating your own attribute that implements ICorsPolicyProvider interface: 这可以通过创建自己的实现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);
    }
}

Then you can use it as follows: 然后,您可以按以下方式使用它:

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