简体   繁体   中英

Enabling Cors in local IIS

I've tried following the steps from Microsoft

https://docs.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

在此处输入图像描述

The problem that I have is when I'm developing and wanted to test, I'm getting errors. 在此处输入图像描述

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.

在此处输入图像描述

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

在此处输入图像描述

when I remove allowCredentials it works but the user doesn't get detected. 在此处输入图像描述

I can reprodcue this issue on my side.

在此处输入图像描述

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

在此处输入图像描述

在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM