Access-Control-Allow-Origin Multiple Origin Domains?

前端 未结 30 2111
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 07:08

Is there a way to allow multiple cross-domains using the Access-Control-Allow-Origin header?

I\'m aware of the *, but it is too open. I rea

30条回答
  •  你的背包
    2020-11-21 07:20

    For a fairly easy copy / paste for .NET applications, I wrote this to enable CORS from within a global.asax file. This code follows the advice given in the currently accepted answer, reflecting whatever origin back is given in the request into the response. This effectively achieves '*' without using it.

    The reason for this is that it enables multiple other CORS features, including the ability to send an AJAX XMLHttpRequest with the 'withCredentials' attribute set to 'true'.

    void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.HttpMethod == "OPTIONS")
        {
            Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            Response.AddHeader("Access-Control-Max-Age", "1728000");
            Response.End();
        }
        else
        {
            Response.AddHeader("Access-Control-Allow-Credentials", "true");
    
            if (Request.Headers["Origin"] != null)
                Response.AddHeader("Access-Control-Allow-Origin" , Request.Headers["Origin"]);
            else
                Response.AddHeader("Access-Control-Allow-Origin" , "*");
        }
    }
    

提交回复
热议问题