[英]Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
I have a CORS Web API controller as shown below 我有一个CORS Web API控制器,如下所示
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AddNewLocationController : ApiController
{
public String Post(String param1, String param2)
{
return "Param1: " + param1 + ", Param2: " + param2;
}
}
I want to pass data to this controller by using Ajax. 我想使用Ajax将数据传递到此控制器。 The command is successful when I add the parameters in the url: 当我在url中添加参数时,命令成功执行:
$.ajax({
url: 'http://localhost:21626/api/AddNewLocation?param1=test1¶m2=chriwil'**,
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
cache: false,
success: function (data) {
console.log(data);
},
error: function (xhr) {
console.log(xhr);
}
});
When I try to pass data using the data property of the ajax call, I get the error "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource" . 当我尝试使用ajax调用的data属性传递数据时,出现错误“对预检请求的响应未通过访问控制检查: 所请求的资源上没有'Access-Control-Allow-Origin'标头” 。
$.ajax({
url: 'http://localhost:21626/api/AddNewLocation',
dataType: "json",
type: "POST",
data: {param1: "param1", param2: "param2chriwil"},
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
cache: false,
success: function (data) {
console.log(data);
},
error: function (xhr) {
console.log(xhr);
}
});
You're not serializing the data. 您没有序列化数据。 The second call should be 第二个电话应该是
data: JSON.stringify({param1: "param1", param2: "param2chriwil"}),
See: jQuery ajax, how to send JSON instead of QueryString 请参阅: jQuery ajax,如何发送JSON而不是QueryString
EDIT 编辑
Additionally if you specify the method signature like Post(String param1, String param2)
the engine will think that the param1
and param2
will come via query string - so no wonder your second invocation fails (you haven't specified the param1
and param2
in url); 另外,如果您指定方法签名,如Post(String param1, String param2)
,引擎将认为param1
和param2
将通过查询字符串来-因此,难怪您的第二次调用失败(您没有在url中指定param1
和param2
) ); if you want to send parameter via json use this signature instead: 如果您想通过json发送参数,请使用以下签名:
public class Model
{
public string param1 { get; set; }
public string param2 { get; set; }
}
public String Post(Model model)
{
return "Param1: " + model.param1 + ", Param2: " + Model.param2;
}
Adding Access-Control-Allow-Origin
header to preflight response in global.asax.cs
worked for me. 在global.asax.cs
向预检响应添加Access-Control-Allow-Origin
标头对我global.asax.cs
。 Please refer https://stackoverflow.com/a/46046766/2847061 请参考https://stackoverflow.com/a/46046766/2847061
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.