others - ASP.NET 检查请求的响应没有通过访问控制检查: 在请求的资源上,不存在'Access Control Allow Origin'

我有一个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&param2=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属性传递数据时,出现错误" Response to preflight request doesn't pass access control check : no'Access-Control-Allow-Origin'header is present on the requested resource ".


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


 }


 });



时间:

你没有序列化数据。


data: JSON.stringify({param1:"param1", param2:"param2chriwil"}),



另外,如果指定方法签名,Post(String param1, String param2)引擎会认为param1param2将通过查询字符串来执行,因此你不奇怪第二个调用失败了;如果要通过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;


} 



添加Access-Control-Allow-Originheader 到global.asax.cs的响应中,请参考https://stackoverflow.com/a/46046766/2847061

...