When I try to call wcf service from $.ajax
method I am getting following Exceptions.
1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
2. Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource.
AJAX Coding
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(request),
async: false,
url: "http://localhost:65201/Empservice.svc/getEmployee",
crossdomain: true,
success: function (data) {
try {
response = data;
}
catch (e) {
alert(e);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Excpetion " + errorThrown + XMLHttpRequest);
}
});
To avoid 405 Method not allowed error try to add following coding in wcf serivce Global.asax file.it working for me
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Accept, Content-Type,customHeader");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"POST,GET,OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
"172800");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials",
"true");
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers",
"customHeader");
HttpContext.Current.Response.AddHeader("Content-type",
"application/json");
HttpContext.Current.Response.End();
}
else
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Accept, Content-Type,customHeader");
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers",
"customHeader");
HttpContext.Current.Response.AddHeader("Content-type",
"application/json");
}
}