C # WEB API CORS not working

Fighting CORS. I have a site that makes a simple XmlHttpRequest for the web API that I built in C #.

    var xhr = new XMLHttpRequest();
    xhr.open("GET","https://server/controller/method", true);
    xhr.send();

In my web.config, I did the following:

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

I also tried installing the Nuget package and doing the following in my WebApiConfig.cs

var cors = new EnableCorsAttribute(
            origins: "*",
            headers: "*",
            methods: "*");
        config.EnableCors(cors);

Despite these efforts, CORS is still not working. In the Firefox console, I get the following error:

Cross-request blocking: the same origin policy prohibits reading the remote resource on the https: // server . This can be fixed by moving the resource to the same domain or by enabling CORS.

IE also just crashes and does not throw errors.

, , , . - / JavaScript? CORS , Visual Studio IIS Express localhost: PortNumber? ?

+5
2

JavaScript- :

xhr.withCredentials = true;

Firefox CORS, , :

Firefox

, , , Access-Control-Allow-Origin *. ...

IIS URL Rewrite Module, Web.config ApplicationHost.config %SystemDrive%\inetpub\wwwroot\.

<configuration> 
    <system.webServer> 
        <rewrite> 
            <outboundRules> 
                <rule name="Make Access-Control-Allow-Origin echo Origin"> 
                    <match serverVariable="RESPONSE_Access-Control-Allow-Origin"
                           pattern=".+" negate="true" /> 
                    <action type="Rewrite" value="{HTTP_ORIGIN}" /> 
                </rule> 
            </outboundRules> 
        </rewrite> 
    </system.webServer> 
</configuration>

, CORS IIS Access-Control-Allow-Origin.

: global.asax , - :

if (ValidateRequest()) {
    Response.Headers.Remove("Access-Control-Allow-Origin");
    Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["origin"]);
    Response.Headers.Remove("Access-Control-Allow-Credentials");
    Response.AddHeader("Access-Control-Allow-Credentials", "true");
    Response.Headers.Remove("Access-Control-Allow-Methods");
    Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}

... :

Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["origin"]);

, Microsoft.AspNet.WebApi.Cors.

+2

web.config, :

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

" ", , , - - , -Credentials, .

, system.webServer.

0

Source: https://habr.com/ru/post/1669960/


All Articles