skip to Main Content

I’ve tried following the steps from Microsoft

https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

I committed the codes I created in GitHub link below

https://github.com/RGatchalian/StackOverflowQuestions/tree/master/ASPNET/EnablingCors

Just to explain, Front-end folder is the call from Javascript to the WebApi and TestingCors folder is the WebApi. I’m currently running this in my local IIS. I deployed the WebApi using Web Deployment and just put the Front-end into inetpub/wwwroot/. And it actually works when both are in localhost

enter image description here

The problem that I have is when I’m developing and wanted to test, I’m getting errors.
enter image description here

The only workaround is to use Chrome with disable-web-security. And it works. I tried changing the WebApiConfig.cs and web.config with what I got from Google but it’s still not working.

enter image description here

UPDATE
Here’s the code

  <system.web>
    <authentication mode="Windows"/>
    <authorization>     
        <allow users="*" />   
    </authorization> 
    <!-- <compilation targetFramework="4.5.2" /> -->
    <!-- <httpRuntime targetFramework="4.5.2" /> -->
    <customErrors mode="Off" />
  </system.web>
  <system.webServer>
    <cors enabled="true" >
        <add origin="*"  />           
    </cors>
  </system.webServer>

This is the error I’m getting when I put allowCredetials

enter image description here

when I remove allowCredentials it works but the user doesn’t get detected.
enter image description here

2

Answers


  1. I can reprodcue this issue on my side.

    enter image description here

    The reason for web browser returning this error is you opened index.htm from physical path and CORS get blocked.

    Please open it from either IIS or IIS express. Then you need to modify your attribute to

     [EnableCors(origins: "http://www.myclient.com", headers: "*", methods: "*", SupportsCredentials = true)]
    

    Finally you will see CORS when you call api from http://www.myclient.com

    enter image description here

    enter image description here

    Login or Signup to reply.
  2. its related to CORS issue. Cross Origin Resource sharing, to resolve you need to enable the cors.
    We can enable CORS three ways:

    1. Global level
    2. controller level
    3. or specific method level

    if you want to enable on method level you can decorate EnableCors attribute, check below code:
    [EnableCors(origins: "", headers: "", methods: "*")]
    you can write specific urls in origin, header also you canset specific header that you are going to pass and method name as where you need to apply.
    I am adding * for all generic(any one can access).

    I hope it would be helpful for you to resolve your issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search