I am developing a C# MVC web application that will send cross domain requests to a Web API REST Service. However I keep on getting errors. My jquery code is as follows:
$.ajax({
url: RESTurl,
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'myCallback'
});
window.myCallback = function (data) {
console.log(data);
};
The webAPI code that is handling my request is like this:
[HttpPost, HttpGet]
public String checkStatus(string passedId)
{
//some other code
return "Status Unavailable";
}
My webApiConfig File is as follows:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{passedId}",
defaults: new { passedId = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));
My issue is that when I type the request in the browser address bar, I get the correct response- Status Unavailable
. (I also get the correct response using postman, but I believe that is because CORS doesn't apply to postman)
I have tried adding crossDomain: 'true'
and adding jquery cross domain plugin to the project, but it hasn't helped.
I have also tried without a callback function but I did not get a result.
Also tried adding Microsoft.AspNet.WebApi.Cors
to the webApi project and then adding
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
to webApiConfig.cs (as suggested here) but it did not make a difference either. I am surprised how there would be a response when typing directly from the browser if there is an issue with CORS. My current response is like this:
http://xxxxx.com:xxxx/xerviceapi/api/xxx/checkstatus/3?callback=myCallback&_=1500087168776
As you might see, my jquery version is 1.10 (little old), but I can't upgrade at the moment as other modules depend on it. Is this a reason?
Also do I need to add a response body to webAPI even though I get a response from the browser? if so how? Please help.