我的测试 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 错误。