我如何读取HttpWebRequest.GetResponse引发WebException时返回的自定义错误消息?
作者:互联网
我有一个具有简单测试方法的NET.Core API:
public async Task<IActionResult> TestApi()
{
try
{
throw new UnauthorizedAccessException("My custom error");
return Ok();
}
catch (UnauthorizedAccessException ex)
{
return StatusCode(401,ex.Message);
}
catch (Exception ex)
{
throw;
}
}
我需要像这样从客户端检索消息:
var request = WebRequest.Create($"{baseUrl}{url}") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.Expect = "application/json";
request.ContentLength = 0;
if (parameters != null)
{
request.ContentLength = serializedObject.Length;
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(serializedObject);
}
}
var response = request.GetResponse() as HttpWebResponse;
var responseEncoding = Encoding.GetEncoding(response.CharacterSet);
using (var sr = new StreamReader(response.GetResponseStream(), responseEncoding))
{
var result = sr.ReadToEnd();
return JsonConvert.DeserializeObject<T>(result);
}
现在以HttpWebResponse的request.GetResponse()返回我:
The remote server returned an error: (401) Unauthorized.
而不是我的自定义错误.有人可以指出我正确的方向吗?
解决方法:
这是一个精简的示例,可读取您的自定义消息.您的消息将在响应流中返回.
try
{
var response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex) // this exception is thrown because of the 401.
{
var responseStream = ex.Response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
var message = reader.ReadToEnd();
}
}
标签:net-core,c 来源: https://codeday.me/bug/20191210/2104465.html