[英]GET works, but POST fails when calling WCF from JQuery on remote server
当我在本地测试CheckGet和CheckPost时,在测试WCF服务上有两个OperationContracts。 当我从Web服务器在Web服务器上同时调用它们时,它们都可以工作,但是当我从本地计算机从远程服务器中调用它们时,CheckGet可以工作,但CheckPost会挂起浏览器窗口。
整个下午,我一直在撞墙,试图弄清楚GET为何起作用,而POST却不起作用。 如果有人可以指出错误的出处,我将不胜感激。
[OperationContract]
[WebGet(UriTemplate = "oAuth/CheckGet")]
string CheckGet();
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "oAuth/CheckPost", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string CheckPost();
只是返回一个基本字符串
public string CheckGet()
{
return "Get is working";
}
public string CheckPost()
{
return "Post is working";
}
我这样称呼他们:
function CheckGet() {
$.ajax({
cache: false,
type: "GET",
async: false,
url: serviceRoot + "CheckGet",
dataType: "json",
timeout: (5 * 1000),
success: function (message) {
alert("Service says - " + message);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
function CheckPost() {
$.ajax({
cache: false,
type: "POST",
async: false,
url: serviceRoot + "CheckPost",
contentType: "application/json",
dataType: "json",
timeout: (5 * 1000),
success: function (message) {
alert("Service says - " + message);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
这是在我的Global.asax文件中
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(oAuth.Services.oAuth)));
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
EnableCrossDmainAjaxCall();
}
private void EnableCrossDmainAjaxCall()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}
更新
这似乎与Global.asax.cs文件有关...
如果我注释掉HttpContext.Current.Response.End(); 那么我至少会得到响应,但是如果那儿存在,则Javascript会挂起,并且服务器上会出现w3wp.exe错误。
POST的AJAX请求JSON作为contentType,这不是WCF的默认值。
尝试像这样装饰您的班级:
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "oAuth/CheckPost",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
string CheckPost();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.