【问题标题】:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】: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&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 属性传递数据时,我收到错误“对预检请求的响应未通过访问控制检查: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);
        }
    });

【问题讨论】:

    标签: asp.net ajax url post


    【解决方案1】:

    您没有序列化数据。第二次调用应该是

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

    见: jQuery ajax, how to send JSON instead of QueryString

    编辑

    此外,如果您指定像 Post(String param1, String param2) 这样的方法签名,引擎将认为 param1param2 将通过查询字符串出现 - 所以难怪您的第二次调用失败(您尚未指定 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;
    }    
    

    【讨论】:

    • 我添加了序列化但我仍然得到同样的错误:“XMLHttpRequest 无法加载localhost:21626/api/AddLocationRating。请求的资源上没有'Access-Control-Allow-Origin'标头。来源'@987654323 @' 因此不允许访问。响应的 HTTP 状态代码为 404。"
    【解决方案2】:

    Access-Control-Allow-Origin 标头添加到global.asax.cs 中的预检响应对我有用。请参考https://stackoverflow.com/a/46046766/2847061

    【讨论】:

      猜你喜欢
      • 2018-05-06
      • 1970-01-01
      • 2017-11-11
      • 2017-04-09
      • 2017-09-08
      • 2017-10-10
      • 2016-12-24
      • 2020-12-07
      相关资源
      最近更新 更多