【发布时间】:2022-09-28 14:23:15
【问题描述】:
在使一些旧的 Web 服务(ASMX - ASp.Net)异步时,在从 javascript 对服务进行 ajax 调用后,我遇到了浏览器中出现错误消息的问题:
Error (RetrieveDD): {
\"readyState\": 4,
\"responseText\": \"System.InvalidOperationException: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.\\r\\n at System.Web.AspNetSynchronizationContext.OperationStarted()\\r\\n at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create()\\r\\n at SearchWebsite.DDService.LoadCountries(Int32 ID)\\r\\n\",
\"status\": 500,
\"statusText\": \"error\"
}
javascript方面:
if (servicename != \"\") {
$.ajax({
url: \'../../DDService.asmx/\' + servicename,
dataType: \'json\',
method: \'post\',
data: { ID: id },
success: function success(data) {
ddl.empty();
if (hid != \"\") {
$.each(data, function () {
if (this[\'V\'] == hid) {
var newOption = new Option(this[\'T\'], this[\'V\'], true, true);
ddl.append(newOption);
} else {
var newOption = new Option(this[\'T\'], this[\'V\'], false, false);
ddl.append(newOption);
}
});
} else {
$.each(data, function (index) {
if (index == 0) {
var newOption = new Option(this[\'T\'], this[\'V\'], true, true);
ddl.append(newOption);
} else {
var newOption = new Option(this[\'T\'], this[\'V\'], false, false);
ddl.append(newOption);
}
});
};
if (typeof callback === \'function\') {
callback(data);
};
},
error: function error(err) {
console.log(\'Error (RetrieveDD): \' + JSON.stringify(err, null, 2));
if (typeof callback === \'function\') {
callback(err);
}
}
});
};
以及webservice中的方法(旧的asmx类型):
[WebMethod(Description = \"Return list of Countries\")]
public async void LoadCountries(int ID)
{
var retval = new List<DDListItemLight>();
retval = await DropDownData.GetCountriesListAsync();
string responseStr = JsonConvert.SerializeObject(retval);
Context.Response.Write(responseStr);
}
无论如何,在我使 webmethod 异步之前,一切正常。 我尝试将签名更改为 公共异步任务 和 公共异步任务 也没有运气。 我认为结束响应会起作用,但它没有效果。
在这里和互联网上环顾四周时,建议将 Async=\"true\" 放在页面标题上 - 但这是一个网络方法而不是 ASPX 页面,所以我希望有一些方法可以使这项工作(使用旧 asmx)。 对此的 MS 文档已有十年之久,并且早于 async/await(我找不到任何示例)
有任何想法吗?
标签: c# asp.net asynchronous webforms asmx