Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (POST request with object)

Viewed 56156

I enabled CORS in my web api application

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

All the requests are working fine. but when i pass an object to the post method i get this:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:44367/api/Users/Create. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

// WORKING
return axios.post(url)
return axios.get(url)


// NOT WORKING

let model = {
    firstName: 'a',
}

return axios.post(url, model);

// or with configuration

let axiosConfig = {
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                "Access-Control-Allow-Origin": true,
                "Access-Control-Allow-Credentials": true,
            }
        };

return axios.post(url, model, axiosConfig);

Also posting with postman is working, with the following body

//{
//  "model" : {
//      "name":"firstName"
//  }
//}

i have set a break-point in Application_BeginRequest event and it wont hit.

Controller Action

public ClientResponseModel<User> Create([FromBody]UserAddModel model)
{
   ///.....
}

Request Header

Host: localhost:44367
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0
Accept: */*
Accept-Language: en,en-US;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-credentials,access-control-allow-origin,content-type
Referer: http://localhost:44346/Registration.aspx
Origin: http://localhost:44346
Connection: keep-alive

Response Header

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/10.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcYWxpLmtcc291cmNlXEF6dXJlXExlYmFuZXNlTGF3c1xDTVNcYXBpXFVzZXJzXENyZWF0ZQ==?=
X-Powered-By: ASP.NET
Date: Mon, 24 Feb 2020 13:56:15 GMT
Content-Length: 0

Any help is really appreciated!

3 Answers
@Bean
public CorsFilter corsFilter() {
   CorsConfiguration corsConfiguration = new CorsConfiguration();
   corsConfiguration.setAllowCredentials(true);
  corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); 
  corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control,     Allow-Origin", "Content-Type", "Accept", "Authorization", "Origin, Accept", "X-Requested-With", "Access-Control-Request-Method", "Access-Control-Request-Header" )); // this allows all headers
   corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization", "Access-Control-Request-Allow-Origin", "Access-Control-Allow-Credentials"));
   corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
    return new CorsFilter();
}

I used this and it work fine for me

I ended up adding the following in my web.config to make it work without any custom configuration on axios:

  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <remove name="OPTIONSVerbHandler"/>
      <remove name="TRACEVerbHandler"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers>
  </system.webServer>

I was getting the same error. I allowed cors from both application side and server side. But after searching, i found out there might be region issue so i added proxy url with the original url and it worked for me. Here is a code:

var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer "+ token);

var requestOptions = {
    
    method: 'GET',
    headers: myHeaders,
    Vary: 'Origin',
};
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "your url";

fetch(proxyurl + url, requestOptions)
    .then(response => response.json())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));
Related