仅针对HttpModule中的特定域启用CORS

时间:2019-04-05 17:53:52

标签: asp.net cors httpmodule

我有一个asp.net Web表单应用程序,我只想对特定域启用CORS。我正在尝试使用HttpModule实现此目的。

例如我的网站是https://mysiteex.com

应该从https://third-party1.comhttps://third-party2.com启用CORS

1 个答案:

答案 0 :(得分:0)

这可能是您要寻找的。将using System.Web;和下面的代码放入Application_BeginRequest事件的Global.asax文件中。

        protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // Enable CORS for cross-site scripting.

        var context = HttpContext.Current;
        var response = context.Response;

        // enable CORS. "*" = all domains, substitute your own as needed.
        response.AddHeader("Access-Control-Allow-Origin", "*");

        if (context.Request.HttpMethod == "OPTIONS")
        {
            response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            response.End();
        }
    }