可以使用以下代码来解决这个问题:
[assembly: System.Web.UI.WebResource("MyNamespace.MyControl.js", "text/javascript")]
[ToolboxData("<{0}:MyControl runat=server>{0}:MyControl>")] public class MyControl : WebControl { protected override void OnInit(EventArgs e) { base.OnInit(e);
if (!this.DesignMode && this.Page != null && this.Page.Header != null)
{
string clientScript = @"function MyControl_OnCallbackComplete(result, context)
{
// Callback code here
}";
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(MyControl), "MyControlScript", clientScript, true);
}
}
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public async Task GetSomeDataAsync(string param)
{
var client = new HttpClient();
HttpResponseMessage result = await client.GetAsync("http://example.com/api/data");
var content = await result.Content.ReadAsStringAsync();
return content;
}
}
这个问题通常是由于您尝试在未绑定Page的ASMX代码中尝试启动异步操作造成的。上面的代码示例演示了如何在OnInit事件中使用ScriptManager,以便正确地启动异步操作。
上一篇:ASMX无法设置已知类型属性
下一篇:ASMX字符串数组到客户端的传递