ASP.NET MVC 开机自检在第一次尝试时无限期等待



我有一个用Html.BeginForm制作的标准表单,它发布到控制器中的异步操作。它看起来像这样(这是一个大纲,而不是实际的代码(:

[HttpPost]
public async Task<ActionResult> Index(UserCreds creds)
{
try
{
if (ModelState.IsValid)
{
var user = await loginRep.Login(creds.Username, creds.Password);
if (user != null)
{
_context.SetAuthenticationToken(user);
return RedirectToAction("Index", "Landing");
} 
else
{
ModelState.AddModelError("", "Login failed.");
}
}
else
{
_logger.Debug(string.Format("User failed authentication."));
}
}
catch (Exception ex)
{
throw new HttpException(500, string.Format("An error occured during the execution of the action {0} from Controller {1}", "Index", "Login"), ex);
}
return View();
}

首次提交表单时,浏览器将无限期地等待响应,即使可以看到使用调试器逐步达到重定向到操作。如果一个人随后在浏览器中停止请求,然后再次提交,则会发生重定向。所有后续登录尝试也会成功重定向。在第一次尝试期间,身份验证令牌也以某种方式未设置。

这可能与loginRep.Login内部的委托使用有关。在它内部最终会做这样的事情:

private async Task<LoginResponse> SendLoginRequest(string username, string password)
{
TaskCompletionSource<LoginResponse> tcs = new TaskCompletionSource<LoginResponse>();
LoginResponseCallback callback = null;
callback = new LoginResponseHandler(delegate (response) {
securityService.OnLoginResponse -= callback;
tcs.SetResult(response);        
});
securityService.OnLoginResponse += callback;
securityService.SendLoginRequest(username, password);
return await tcs.Task;
}

有谁明白发生了什么?如果是死锁,我不希望看到调试器到达重定向,也不会期望登录适用于除第一次尝试以外的所有尝试。

请注意,如果只是跳过发送登录请求并仅对成功响应的外观进行硬编码,则该表单在第一次确实有效。

好的。问题已解决。我展示的两个代码示例没有任何问题。错误出在设置我的安全服务时,因此不幸的是,它非常特定于此应用程序。

也就是说,无限等待的发生是因为 Global.asax.cs 中的Application_Error有效地吞噬了某些异常。一旦我将其更改为无论如何始终重定向到我的错误页面,至少它在问题发生时立即重定向到错误页面,而不是从用户的角度挂起。

最新更新