Reputation: 2235
I'm trying to send the following object to my Web API Rest service using jQuery's $.ajax() method. When I make the call with out setting content type explicitly it sets it to application/x-www-form-urlencoded automatically, and the response is a 500. I need it to be application/json. When I set it to contentType: 'application/json' the request method in the header suddenly says OPTIONS in the dev tools and the request returns a 405. Does anyone see anything I'm doing wrong here? I normally never have trouble making requests like this.
Here is the data object I'm sending.
var TEST_DATA = {
PaitentId: "323f0725-b404-4ab3-b227-e64b090ff62f",
PracticeId: "2387B1BE-6CEC-41C1-B411-687BD6160556",
ReportName: "SOME_REPORT_NAME",
DeviceId: 1,
GlucoseUnits: 1,
HighGlucoseThreshold: 185,
LowGlucoseThreshold: 80,
TodayDate: "\/Date(1382932800000)\/",
StartDate: "\/Date(1357016400000)\/",
EndDate: "\/Date(1411876800000)\/"
}
Here is the call I'm making to the api
var GenerateReport = function () {
$.ajax({
type: 'POST',
url: SERVICE_URL,
processData: false,
dataType: 'json',
contentType: 'application/json',
data: TEST_DATA,
crossDomain: true,
beforeSend: displaySpinner(),
success: function (data) {
successCallback(data);
},
error: function () {
errorCallback();
}
});
}
EDIT: This ended up being something I could fix through Web API, Answer provided below.
Upvotes: 0
Views: 163
Reputation: 2235
So I ended up fixing the issue by allowing CORS to be used directly through web API. The Documentation can be found here http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
You add config.EnableCors();
to your WebApiConfig
class. Then in your controller you can add an attribute like below
namespace WebService.Controllers
{
[EnableCors(origins: "http://your.origin.site.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
You can do this globally as well through the WebApiConfig
as well.
Upvotes: 0
Reputation: 149135
If you are trying to do a cross domain request, it is by design. The documentation of jQuery.ajax
says : Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.
You should not use Json for cross-domain web service.
Upvotes: 3