使用jQuery的$ .ajax()调用C#异步WebMethod无休止地挂起

时间:2017-08-03 14:31:15

标签: c# jquery ajax asynchronous async-await

问题:

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

当我实施asyncawait时,会调用Web方法,但调用永远不会完成。 Chrome会将响应显示为“(待定)“,时间选项卡显示呼叫”已停顿“

非常感谢任何输入。

我试过了:

  • 未使用asyncawait

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

  • Task<bool>更改为void

      

    “此时无法启动异步操作。”

    (是的,我的页面 标记为Async="true"

  • 谷歌搜索并搜索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;
}

3 个答案:

答案 0 :(得分:1)

我很抱歉并且松了一口气,我可以在问这么短的时间后向我自己的问题发布一个解决方案,但我暂时想出了一个解决方案。虽然,我不会接受我自己的答案,因为我仍然喜欢一些输入。

我已将我的网络方法重新计算为标准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);
}

答案 1 :(得分:0)

两年后,很难过,没有人提供答案。基本上:

bool profileUpdated =  await ExampleApi.UpdateProfile(profile).ConfigureAwait(false);

这将配置任务,以便它可以在与启动时不同的线程上继续执行。恢复后,您的会话将不再可用。如果您不使用ConfigureAwait(false),那么它将永远等待调用线程可用,这不会发生,因为它还在调用链中进一步等待。

但是,我遇到了无法发送返回值的问题。如果Async = true,则调用WebMethod的asp.net引擎应该等待结果,但这对我来说似乎没有发生。

答案 2 :(得分:0)

在这一行>

bool profileUpdated = await ExampleApi.UpdateProfile(profile);

除了跟在调用栈后面的所有其他方法外,这个方法还必须是静态和异步的。

另一个重要的点是用 async: true 标记你的 ajax 调用,

相关问题