c# - 使用 jQuery 的 $.ajax() 调用 C# async WebMethod 无限挂起

标签 c# jquery ajax asynchronous async-await

问题:

我正在尝试从 jQuery 调用 C# Web 方法来更新用户的个人资料。

当我执行 async 时和 await ,调用 Web 方法但调用永远不会完成。Chrome 永远将响应显示为“(待定)”,并且“时间”选项卡显示调用是“停滞不前”

非常感谢任何输入。


我试过:

  • 未使用 asyncawait

    有效!然而,这完全违背了我想要实现的目标。


  • 改变 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/

相关文章:

c# - 为什么在没有 .NET 的 Reactive(Rx) 扩展的情况下不能使用 IObservable<T>?

c# - 静态类和单例类性能有什么区别(内存管理)

javascript - 如何检查特定对象键并在存在时进行更新

javascript - 使用 javascript 上传文件(iPad Web 应用程序)

javascript - keydown 上的 jQuery 下拉 ajax 搜索是 'one step behind'

c# - 如何创建一个新的 FlatButtonAppearance 对象?

c# - .Net Blazor 优于 Angular、React 或其他 javascript 框架

javascript - 覆盖 jQuery 函数中的客户端错误消息,以便可以添加值

jquery - Microsoft JScript 运行时错误 : Object doesn't support property or method 'fileUpload'

javascript - jQuery.ajax() 不触发处理程序