当我尝试从$.ajax
方法调用wcf服务时,我得到了以下异常。
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编码
$.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);
}
});
答案 0 :(得分:1)
为避免405方法不允许出错,请尝试在wcf serivce Global.asax file.it中为我添加以下编码
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");
}
}