【发布时间】:2016-02-23 12:25:49
【问题描述】:
我有一个如下所示的 CORS Web API 控制器
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AddNewLocationController : ApiController
{
public String Post(String param1, String param2)
{
return "Param1: " + param1 + ", Param2: " + param2;
}
}
我想使用 Ajax 将数据传递给这个控制器。当我在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);
}
});
当我尝试使用 ajax 调用的 data 属性传递数据时,我收到错误“对预检请求的响应未通过访问控制检查:No 'Access-Control-Allow-Origin' header is出现在请求的资源上”。
$.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);
}
});
【问题讨论】: