我在测试WCF服务上有两个OperationContracts,当我在本地测试CheckGet和CheckPost工作时。当我在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错误。
答案 0 :(得分:0)
您的POST的AJAX请求JSON作为contentType,这不是WCF的默认值。
尝试像这样装饰你的课:
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "oAuth/CheckPost",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
string CheckPost();