背景
目前正在创建一个 Web API,它需要与我创建的另一个 Web API 通信。这个有问题的 web api 是开箱即用的,我唯一生气的改变是启用核心并向其添加两个类。
问题
目前,此 Web API 一直执行到我的集成点,但是当它遇到 HttpResponseMessage hrm = await hc.GetAsync(requestUrl);
时,它停止并且没有给我错误。我尝试对该函数进行 try catch,但它也忽略了 try catch。以下代码将展示我如何构建此 Web API。
代码
Controller
[Route("api/WorkingPaperServices/CreateWorkingPaper")]
public IHttpActionResult CreateWorkingPaper()
{
try
{
log4net.Config.XmlConfigurator.Configure();
bool complete = WorkingPaperCreator.StartWPCreation().Result;
return Ok("Finished");
}
catch(Exception ex)
{
log4net.LogManager.GetLogger("EmailLogger").Error(JsonConvert.SerializeObject(ex));
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Not Laoded"));
}
}
WorkingPaperCreator - 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace CWAppServices.Services
{
public class WorkingPaperCreator
{
public static async Task<bool> StartWPCreation()
{
try
{
var testing = await IntergrationPoints.GetClientInformation();
return true;
}
catch(Exception ex)
{
return false;
}
}
}
}
IntergrationPoints - 类(我的问题在哪里)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
namespace CWAppServices.Services
{
public class IntergrationPoints
{
public static async Task<bool> GetClientInformation()
{
List<string> uniqueID = new List<string>();
try
{
string requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/GetAllClients";
var action = new HttpMethod("GET");
HttpClient hc = new HttpClient();
HttpResponseMessage hrm = await hc.GetAsync(requestUrl);
if (hrm.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
// TODO Log
return false;
}
}
}
}
最佳答案
这个阻塞调用导致了问题:
bool complete = WorkingPaperCreator.StartWPCreation().Result;
。
你得到死锁。为避免它在任何地方使用 aync\await(也使您的 Controller 异步)或将 .ConfigureAwait(false)
添加到所有 await 调用。
关于c# - 异步功能未完成,但我没有收到任何错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43118461/