前言
.Net程序中在执行了await方法后,再次获取HttpContext.Current时,值为null,可以通过如下方法解决此问题
解决方案
主要代码:
var tempHttpContextCurrent = System.Web.HttpContext.Current;//在执行await之前,将HttpContext.Current赋值给变量
HttpResponseMessage response = await client.PutAsync("api/EditUser", content);
System.Web.HttpContext.Current = tempHttpContextCurrent;//在执行完await后,将变量赋值给HttpContext.Current
public void updateuser(){
var tempHttpContextCurrent = System.Web.HttpContext.Current;//在执行await之前,将HttpContext.Current赋值给变量
var client = CurrentUser.CallServices.GetAPIClient();
UserInfo userinfo = new UserInfo();
userinfo.U_userId = 8;
userinfo.U_description = Description;
userinfo.U_displayName = DisplayName;
userinfo.U_distinguishedName = sAMAccountDN;
userinfo.U_sAMAccountName = sAMAccountName;
userinfo.U_status = 1;
string json = JsonConvert.SerializeObject(userinfo);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PutAsync("api/EditUser", content);
System.Web.HttpContext.Current = tempHttpContextCurrent;//在执行完await后,将变量赋值给HttpContext.Current
if (response.IsSuccessStatusCode)
{
//再次获取System.Web.HttpContext.Current时候可以正常获取到其值
}
else
{
//再次获取System.Web.HttpContext.Current时候可以正常获取到其值
}
}
/// <summary>
/// 调用webapi接口 通过httpclient
/// </summary>
/// <returns></returns>
public static HttpClient GetAPIClient()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44344/");
// Add an Accept header for JSON format.
// 为JSON格式添加一个Accept报头
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
//Controller方法
// PUT api/values/5
[HttpPut]
[Route("api/EditUser")]
public bool EditUser([System.Web.Http.FromBody] UserInfo model)
{
var UserInfoRepository = new UserInfoRepository();
bool result = UserInfoRepository.Update(model);
return result;
}