2

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);
        }
    });
Christopher Wilke
  • 65
  • 1
  • 1
  • 10

2 Answers2

4

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;
}    
Community
  • 1
  • 1
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
  • I added the serializtion but I still get the same error: "XMLHttpRequest cannot load http://localhost:21626/api/AddLocationRating. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:46666' is therefore not allowed access. The response had HTTP status code 404." – Christopher Wilke Nov 21 '15 at 16:42
0

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

nik
  • 2,455
  • 21
  • 26