我有一个服务调用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");
}
然而,当我测试它时,在我点击Login(触发后请求(后,我可以告诉GET在我的flask 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);
// ...
}
这样你的意图会更清晰,也更容易把事情做好。