如何读取 HttpWebRequest.GetResponse 引发 WebException 时返回的自定义错误消息? [英] How do I read a custom error message returned when HttpWebRequest.GetResponse throws a WebException?

查看:16
本文介绍了如何读取 HttpWebRequest.GetResponse 引发 WebException 时返回的自定义错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有简单测试方法的 NET.Core API:

I've a NET.Core API with simple test method:

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

}

我需要像这样从客户端检索消息:

I need to retrieve the message from a client like this:

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.

而不是我的自定义错误.有人能指出我正确的方向吗?

instead of My custom error. Can someone point me in the right direction?

推荐答案

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

Here's a pared-down example which reads your custom message. Your message is returned in the response stream.

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

这篇关于如何读取 HttpWebRequest.GetResponse 引发 WebException 时返回的自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆