问题:
我正在尝试从 jQuery 调用 C# Web 方法来更新用户的个人资料。
当我执行 async
时和 await
,调用 Web 方法但调用永远不会完成。Chrome 永远将响应显示为“(待定)”,并且“时间”选项卡显示调用是“停滞不前”。
非常感谢任何输入。
我试过:
未使用
async
和await
有效!然而,这完全违背了我想要实现的目标。
改变
Task<bool>
至void
:"An asynchronous operation cannot be started at this time."
(是的,我的页面被标记为
Async="true"
)
Google 搜索 SO:
我发现了一些类似的问题,但得到的答案要么是“让它同步吧!”(这完全违背了目的),要么是我不希望的 MVC 解决方案在我当前的项目中工作。
代码:
$.ajax({
type: "POST",
url: "Profiles.aspx/updateProfileName",
data: JSON.stringify({
profileName: $input.val(),
customer_profile_id: cp_id
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: callSuccessful,
error: callFailed
});
[WebMethod]
public static async Task<bool> updateProfileName(string profileName, string customer_profile_id)
{
User user = (User) HttpContext.Current.Session["user"];
if (profileName.Trim().Length == 0) return false;
int customerProfileId = int.Parse(customer_profile_id);
CustomerProfileViewModel profile = new CustomerProfileViewModel();
profile.profile_name = profileName;
profile.customer_profile_id = customerProfileId;
profile.customer_id = user.customerId;
bool profileUpdated = await ExampleApi.UpdateProfile(profile);
return profileUpdated;
}
最佳答案
对于我能够在提出自己的问题后这么短的时间内发布解决方案,我感到既抱歉又欣慰,但我暂时想出了一个解决方案。虽然,我不会接受我自己的回答,因为我仍然希望有一些意见(如果有的话)。
我已经将我的 Web 方法重构为标准的 public static bool
而不是 async
。它不再包含 await
,而是使用 Task.Run()
来调用 async await
函数:
public static bool updateProfileWebMethod(string profileName, string customer_profile_id)
{
User user = (User) HttpContext.Current.Session["user"];
if (profileName.Trim().Length == 0) return false;
int customerProfileId = int.Parse(customer_profile_id);
CustomerProfileViewModel profile = new CustomerProfileViewModel();
profile.profile_name = profileName;
profile.customer_profile_id = customerProfileId;
profile.customer_id = user.customerId;
//CALL THE ASYNC METHOD
Task.Run(() => { updateProfileName(profile); });
return true;
}
public static async void updateProfileName(CustomerProfileViewModel profile)
{
bool profileUpdated = await ExampleApi.UpdateProfile(profile);
}
关于c# - 使用 jQuery 的 $.ajax() 调用 C# async WebMethod 无限挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45487200/