簡體   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