如何读取HttpWebRequest.GetResponse引发WebException时返回的自定义错误消息?

时间:2019-05-30 14:45:33

标签: c# .net-core

我有一个使用简单测试方法的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);
}

现在request.GetResponse() as HttpWebResponse返回了我:

The remote server returned an error: (401) Unauthorized.

enter image description here

而不是My custom error。有人可以指出我正确的方向吗?

2 个答案:

答案 0 :(得分:2)

这是一个精简的示例,可读取您的自定义消息。您的消息将在响应流中返回。

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();
    }
}

答案 1 :(得分:0)

返回ActionResult

Task<ActionResult>

然后您可以将未授权的错误包装在UnauthorizedObjectResult中

return Unauthorized(new UnauthorizedObjectResult(errorModel));