我一直试图了解AJAX和异步Web API,但是我一直遇到一些问题,我的AJAX启用WCF正在定义异步方法。我跟着this MSDN example来启用支持AJAX的WCF使用同步方法就好了,但如果我添加一个列为async的新方法,所有方法都会停止工作。以下是我所拥有的例子。
SampleAJAX.svc.cs
namespace SimpleSample
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SampleAJAX
{
[OperationContract]
public string GetServiceName()
{
return "SampleAJAX";
}
}
}
我的Default.aspx中的JavaScript示例:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SimpleOAuthSample.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test AJAX WCF Async</title>
<script>
function Button1_onclick() {
var service = SampleAJAX;
service.GetServiceName(onSuccessPopUp, null, null);
}
function onSuccessPopUp(result){
alert(result);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div></div>
<asp:scriptmanager runat="server">
<Services>
<asp:ServiceReference Path="SampleAjax.svc" />
</Services>
</asp:scriptmanager>
</form>
<p><input id="Button1" type="button" value="Call Example Service" onclick="Button1_onclick()"/></p>
</body>
</html>
这看起来效果很好,但是当我将它添加到SampleAJAX.cvs.cs时,原始的GetServiceName()不再起作用,新的异步版本也不行。我在方法和附加的调试器中有断点,但是一旦我添加异步方法它们就永远不会被击中。
[OperationContract]
public async Task<string> GetServiceNameAsync()
{
await Task.Delay(2000);
return "SampleAJAX asynchronous";
}
关于我缺少的任何想法?我确信这很简单。