首页 > 解决方案 > 您可以通过在异步方法上调用 .Result 在 HTTP POST 中执行 GET 请求吗?

问题描述

我有一个调用 API GET 请求并返回布尔值的服务。

Task<bool> LoginExist(string email, string password);

在控制器中,我有以下代码:

    [HttpPost]
    public ActionResult Login(string email, string password)
    {
        System.Diagnostics.Debug.WriteLine("here");
        bool login_result = _accountService.LoginExist(email, password).Result;
        System.Diagnostics.Debug.WriteLine(login_result);

        if (login_result)
        {
            FormsAuthentication.SetAuthCookie(email, false);
            return Redirect(Request.UrlReferrer.ToString());
        }
        else
        { Redirect("Register"); }

        return Redirect("Register");
    }

但是,当我测试它时,在我单击触发发布请求的登录后,我可以告诉 GET 在我的烧瓶 api 中成功执行(它返回状态 200),但是,它永远不会进入代码中的 IF 语句或 ELSE 语句以上。相反,它只是继续运行......

我想知道我们是否可以在 POST 中使用 GET,如果不能,有没有人有更好的方法来解决这个问题?

我添加了我的服务:

    public async Task<bool> LoginExist(string email, string password)
    {
        string url = string_url;
        LoginVerification str = await url.WithHeaders(new { Accept = "application /json", User_Agent = "Flurl" }).GetJsonAsync<LoginVerification>();

        return str.login_valid;
    }

标签: c#pythonflaskhttp-posthttp-get

解决方案


这里的问题与 GET 与 POST 无关。这就是您使用异步方法的方式。直接访问Result属性不是获取异步任务结果的正确方法。

将其更改为调用GetAwaiterGetResult如下所示:

bool login_result = _accountService.LoginExist(email, password).GetAwaiter().GetResult();

或者更好的是,制定您的操作方法async并使用await关键字等待结果。

[HttpPost]
public async Task<ActionResult> Login(string email, string password)
{
    // ...
    bool login_result = await _accountService.LoginExist(email, password);
    // ...
}

这样你的意图会更清晰,也更容易把事情做好。


推荐阅读