跨域请求被阻止:同源策略禁止读取远程资源(带有对象的POST请求)

时间:2020-02-24 14:16:03

标签: ajax axios asp.net-web-api2 httprequest asp.net-ajax

我在Web api应用程序中启用了CORS

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

所有请求均正常运行。但是when i pass an object to the post method我得到了:

跨域请求被阻止:“同源起源”策略不允许读取http://localhost:44367/api/Users/Create处的远程资源。 (原因:CORS标头“ Access-Control-Allow-Origin”缺失)。

// 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);

还可以在以下正文中与邮递员一起发帖

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

我在Application_BeginRequest事件中设置了一个断点,但不会成功。

控制器动作

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

请求标头

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

响应标题

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

我们非常感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

@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();
}

我用过这个,对我来说效果很好

答案 1 :(得分:0)

我最终在web.config中添加了以下内容,以使其在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>

答案 2 :(得分:0)

我遇到了同样的错误。我从应用程序端和服务器端都允许使用cors。但是在搜索之后,我发现可能存在区域问题,因此我在原始URL中添加了代理URL,它对我有用。这是代码:

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));

答案 3 :(得分:-1)

这是典型的cors问题,请阅读下面的链接,这可能有助于您了解为什么发生此错误。

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

技术,当您的页面域名与请求网址不同时,浏览器将阻止您的xhr请求。您的服务器应使用标头Access-Control-Allow-Origin: <origin of your client page> | *

进行响应