How to fix CORS issue during development with localhost different port

Pragyan Snata 20 Reputation points
2023-02-06T04:53:41.13+00:00
Hello,

I have  a Angular Js  application and backend WCF service c# .net  , both are running in localhost IISExpress with different port.

Client UI is accessing WCF API through http POST/GET.

While debugging from Visual Studio using Edge it's throwing Cors issue--- Access to XMLHttpRequest at  http://localhost:60000/  from origin  http://localhost:30000/ has been blocked by CORS policy: Response to preflight request doesn't pass access control check.

I have tried to install  

I have added

             <add name="Access-Control-Allow-Origin" value="*"/>

              <add name="Access-Control-Allow-Methods" value="*"/>

              <add name="Access-Control-Allow-Headers" value="*"/>

              <add name="Access-Control-Allow-Credentials" value="true"/>

              <add name=" Access-Control-Allow-Private-Network" value="true"/>

in web .config still not working. 

I really need some solution to disable CORS during development.

System Info - Windows 10 Enterprise 64 bit OS
Microsoft 365 and Office | Development | Office JavaScript API
Developer technologies | .NET | Other
Developer technologies | ASP.NET | Other
{count} votes

1 answer

Sort by: Most helpful
  1. Naimish Makwana 175 Reputation points
    2023-02-06T05:08:08.5433333+00:00

    Hello Pragyan,

    Add this method to the 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");
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                    HttpContext.Current.Response.End();
                }
            }
    

    Also for more details refer below link.

    https://www.codeproject.com/Articles/845474/Enabling-CORS-in-WCF

    https://stackoverflow.com/a/26040237/3054222

    Thanks

    Naimish Makwana

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.