它运行良好,但是我在api中进行了一些更改,没有添加更多的控制器,然后它停止工作,并始终抛出异常:GetAsync()行中的“ TaskCanceledException:任务已取消” )。结果。我增加了超时时间并无限地保持加载状态。 向控制器API发出请求的代码控制器APP:
public ActionResult Login(LoginM us)
{
try
{
cuentaM account = new cuentaM();
HttpClient client = new HttpClient();
var result = client.GetAsync("http://localhost:26723/api/Login" + "?email=" + us.email + "&password=" + us.password).Result;
if (result.IsSuccessStatusCode)
{
account = result.Content.ReadAsAsync<cuentaM>().Result;
}
Session["cuenta"] = account;
return RedirectToAction("Index", "Home");
}
catch (Exception ex)
{
throw;
}
}
控制器API代码:
public HttpResponseMessage Get(string email, string password)
{
try
{
using (elevationbEntities db = new elevationbEntities())
{
usuario user = db.usuarios.Where(m => m.email == email && m.password == password).SingleOrDefault();
cuentaM account = new cuentaM();
if (user != null)
{
account = (from o in db.cuentas
join cu in db.cuentausuarios on o.idCuenta equals cu.idCuenta
join u in db.usuarios on cu.idUsuario equals u.idUsuario
where u.idUsuario == user.idUsuario
select new cuentaM { idUsuario = user.idUsuario, idCuenta = o.idCuenta, CodigoUnico = o.CodigoUnico })
.FirstOrDefault();
}
else
{
account.Error = "Wrong Password or Email";
}
HttpResponseMessage response;
response = Request.CreateResponse(HttpStatusCode.OK, account);
return response;
}
}
catch (TaskCanceledException ex)
{
HttpResponseMessage response;
response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
return response;
}
}
答案 0 :(得分:0)
在submit
的异步API上进行阻塞调用(.Result
)可能导致死锁,尤其是在被用作asp.net MVC的情况下,该死锁可能在进行阻塞调用时调用了异步操作。 / p>
使代码一直保持异步。
也请尝试避免在每个请求上创建HttpClinet
的实例。这可能会导致插槽用尽。
HttpClient
答案 1 :(得分:0)
您可能会因阻塞异步调用而陷入僵局,如this article中所述。这是有问题的行:
private static HttpClient client = new HttpClient();
public async Task<ActionResult> Login(LoginM us) {
try {
cuentaM account = new cuentaM();
var url = "http://localhost:26723/api/Login" + "?email=" + us.email + "&password=" + us.password
var result = await client.GetAsync(url);
if (result.IsSuccessStatusCode) {
account = await result.Content.ReadAsAsync<cuentaM>();
}
Session["cuenta"] = account;
return RedirectToAction("Index", "Home");
} catch (Exception ex) {
throw;
}
}
将account = result.Content.ReadAsAsync<cuentaM>().Result;
的方法签名更改为:
Login
然后将有问题的行更改为使用 public async Task<ActionResult> Login(LoginM us)
而不是await
:
.Result