【问题标题】:C# how create WebException with Response status codeC#如何使用响应状态码创建WebException
【发布时间】:2016-07-21 07:08:29
【问题描述】:

我做了一些假课程,它应该与原始课程具有相同的行为。 原始类有时会抛出 WebExceptions(使用 StatusCode 来自服务器的响应)。

我想在没有任何联系的情况下重复此行为。 那么,我怎样才能用需要的StatusCode 创建new WebException(..., ..., ..., ...)

【问题讨论】:

    标签: c# exception http-status-codes webexception


    【解决方案1】:

    这里棘手的部分是,虽然WebException(String, Exception, WebExceptionStatus, WebResponse) 构造函数是免费提供的,但HttpWebResponse 被声明只能通过HttpWebRequest 创建(有构造函数,但它们已经过时了)。

    所以,由于WebException 接受抽象WebResponse 而不是HttpWebResponse,我建议创建一个类MockHttpWebResponse 或其他东西。我不知道您确切需要哪些变量,所以我会将您链接到HttpWebResponse source,以便您从中清除基本变量。

    然后你在构造函数中使用这个类,如下所示:

    new WebException(message, null, WebExceptionStatus.ProtocolError, new MockHttpWebResponse(statusCode))
    

    ...或类似的东西。我想你最清楚你的场景需要什么。 ;)

    【讨论】:

      【解决方案2】:

      需要自定义一个类来增加HTTP状态码:

      public class HttpWebException : WebException
      {
          public int HttpStatusCode { get; set; }        
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用反射来实现这一点。在以下示例中,我创建了一个 Web 异常,并调整了响应(也使用反射)。

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        statusCode = (int)response.StatusCode;
        ActivateCallback(responseCallback, response, url, string.Empty);
        
        var fieldStatusCode = response.GetType().GetField("m_StatusCode", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        {
            var statusCodeNew = (HttpStatusCode)403;
            fieldStatusCode.SetValue(response, statusCodeNew);
        }
        
        
        string responceBody = "{\"error\":{\"code\":\"AF429\",\"message\":\"Too many requests. Method=GetContents, PublisherId=00000000-0000-0000-0000-000000000000\"}}";
        
        var propStream = response.GetType().GetField("m_ConnectStream", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        
            System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(responceBody));
            //response.ResponseStream = ms;//((System.Net.ConnectStream)(response.ResponseStream))
            propStream.SetValue(response, ms);
            ms.Position = 0;
        
        
        WebException ex1 = new WebException();
        var fieldResponce = ex1.GetType().GetField("m_Response", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        {
            fieldResponce.SetValue(ex1, response);
        }
        e = null;
        throw ex1;
        

        【讨论】:

          猜你喜欢
          • 2017-10-19
          • 1970-01-01
          • 1970-01-01
          • 2022-06-18
          • 2019-04-06
          • 1970-01-01
          • 2021-07-21
          • 1970-01-01
          • 2021-09-19
          相关资源
          最近更新 更多