Issue in Enabling CORS for Web API 1, .net 4.0

后端 未结 2 1208
独厮守ぢ
独厮守ぢ 2021-01-07 06:57

I need to enable CORS for my Web API and I can\'t upgrade to Framework 4.5. I\'ve tried to add the following to my Web.config to see if it worked, but it didn\'t:

         


        
相关标签:
2条回答
  • 2021-01-07 07:38

    Web API 1.0, you need to enable CORS support using the following statements in the Application_BeginRequest event handler of the Global.asax.cs file.

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", allowedOrigin);
    

    Support for CORS can be enabled at three levels. These include the following:

    Action level Controller level Global level

    refer link

    0 讨论(0)
  • 2021-01-07 07:45

    I found this simple solution by charanjit singh. It worked nicely especially if you are stuck with older visual studio 2010 , on .Net 4.0 and of course web api 1. Basically add this function to your Global.asax.cs

    protected void Application_BeginRequest(object sender, EventArgs e)
    
    {
    
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                         "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                         "Content-Type, Accept");
            HttpContext.Current.Response.End();
         }
    } 
    

    ref. links: note you must scroll to the bottom comments for the answer. http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html

    0 讨论(0)
提交回复
热议问题