c# - 您可以通过在异步方法上调用 .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;
}
解决方案
这里的问题与 GET 与 POST 无关。这就是您使用异步方法的方式。直接访问Result
属性不是获取异步任务结果的正确方法。
将其更改为调用GetAwaiter
,GetResult
如下所示:
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);
// ...
}
这样你的意图会更清晰,也更容易把事情做好。
推荐阅读
- javascript - Javascript:参数可以是任何东西吗?
- python - 如何在 Django 上使用 POST 传递值?
- vba - 如何强制 Application.Volatile 结束或特定工作簿/工作表
- cobalt - 如何将系统语言设置转移到钴
- c++ - 为什么我在声明类对象时无法初始化它?
- c# - 如何设置 bsonDocument 的 id?
- oracle - Oracle 11 主键生成
- javascript - 处理 vuex 中的嵌套/复杂对象
- php - 如何使用 Google QR Code API 通过 PHP 将 QR 图像保存到数据库?
- javascript - NodeJS:为什么在用户注册期间未定义电子邮件?