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¶m2=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);
}
});
You're not serializing the data. The second call should be
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 theparam1
andparam2
will come via query string - so no wonder your second invocation fails (you haven't specified theparam1
andparam2
in url); if you want to send parameter via json use this signature instead:Adding
Access-Control-Allow-Origin
header to preflight response inglobal.asax.cs
worked for me. Please refer https://stackoverflow.com/a/46046766/2847061