Response to preflight request doesn't pass acc

2019-05-23 09:25发布

I have a CORS Web API controller as shown below

[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. The command is successful when I add the parameters in the 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);
        }
    });

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

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-23 09:34

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

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); if you want to send parameter via json use this signature instead:

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;
}    
查看更多
3楼-- · 2019-05-23 09:43

Adding Access-Control-Allow-Origin header to preflight response in global.asax.cs worked for me. Please refer https://stackoverflow.com/a/46046766/2847061

查看更多
登录 后发表回答