C# System.Net.WebException 检索自定义 404 消息

标签 c# system.net.webexception

我正在为返回标准状态代码(404、200 等)的网络服务开发客户端 以及自定义 json 消息。

我无法找到包含自定义消息的 WebException 的属性。

关于如何获取消息的任何想法?

最佳答案

简单的解决方案:

WebException 在 Response 属性中有可用的实际 WebResponse。 从这里开始,只需按正常方式处理响应即可:

    private static JsonParseException ProcessException(WebException webEx)
    {
        var stream = webEx.Response.GetResponseStream();
        using (var memory = new MemoryStream())
        {
            var buffer = new byte[4096];
            var read = 0;
            do
            {
                read = stream.Read(buffer, 0, buffer.Length);
                memory.Write(buffer, 0, read);

            } while (read > 0);

            memory.Position = 0;
            int pageSize = (int)memory.Length;
            byte[] bytes = new byte[pageSize];
            memory.Read(bytes, 0, pageSize);
            memory.Seek(0, SeekOrigin.Begin);
            string data = new StreamReader(memory).ReadToEnd();

            memory.Close();
            DefaultMeta meta = JsonConvert.DeserializeObject<DefaultMeta>(data);
            return new JsonParseException(meta.Meta, meta.Meta.Error, webEx);
        }
    }

我正在使用 NewtonSoft Json 库反序列化 Json 响应

关于C# System.Net.WebException 检索自定义 404 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1824220/

相关文章:

c# - 如何解决 .NET.CORE 中的代理服务器 407 错误

c# - HttpWebRequest - GetResponse() - WebException ReceiveFailure

c# - 如果我正在使用的 Web 服务超时,会抛出什么异常?

c# - 简单 C# 中的 DI 和 IOC 示例

c# - 如何验证 RSA 公钥?

c# - "Getters should not include large amounts of logic."是真是假?

c# - 请求在 Helper 方法上被中止 : The connection was closed unexpectedly.

c# - C# 中的 403 响应主体的方法似乎不可用

使用 Entity Framework 6 异常数据读取器的 C# 存储库模式 SQL 查询与指定实体不兼容

c# - 获取类型的转换器