Christopher Wilke
Christopher Wilke

Reputation: 65

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

[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);
        }
    });

Upvotes: 2

Views: 33613

Answers (2)

nik
nik

Reputation: 2483

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

Upvotes: 0

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22054

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;
}    

Upvotes: 4

Related Questions