它工作得很好,但我在应用程序接口中做了一些更改,添加了更多的控制器,没有任何异常,然后它停止工作,总是在GetAsync().result行中抛出异常:"TaskCanceledException:一个任务被取消“。我增加了超时时间,并且无限地保持加载。向控制器API发出请求的代码控制器应用程序:
public ActionResult Login(LoginM us) 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) 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(); 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; }
上云精选
2核2G云服务器 每月9.33元起,个人开发者专属3年机 低至2.3折
在 HttpClinet 的异步API上进行阻塞调用( .Result )可能会导致死锁,特别是在使用MVC时,当进行阻塞调用时,可能会调用异步操作。
HttpClinet
.Result
让代码一直保持同步。
同时,尽量避免在每次请求时都创建 HttpClient 实例。这可能会导致套接字耗尽。
HttpClient
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>();