5

I make some fake class, that should have same behavior as original one. Original class sometimes throws WebExceptions (with StatusCode in response from server).

I want repeat this behavior without any connection. So, how can i create new WebException(..., ..., ..., ...) with needed StatusCode

murzagurskiy
  • 1,273
  • 1
  • 20
  • 44

3 Answers3

3

You need to customize a class to increase the HTTP Status Code:

public class HttpWebException : WebException
{
    public int HttpStatusCode { get; set; }        
}
Fan TianYi
  • 397
  • 2
  • 11
2

The tricky part here is that while WebException(String, Exception, WebExceptionStatus, WebResponse) constructor is freely available, the HttpWebResponse is stated to be created only through HttpWebRequest (there are constructors, but they are obsolete).

So, since WebException accepts abstract WebResponse rather than HttpWebResponse, I suggest creating a class MockHttpWebResponse or something. I don't know which variables you need exactly, so instead I'll link you to HttpWebResponse source for you to scavenge essential variables from.

Then you use this class in constructor like here:

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

...or something similar. I think you know best what's needed for your scenario. ;)

Alice
  • 585
  • 5
  • 16
0

You can use reflections to accomplish that. In the following example i created a web exception with response i adjusted (also using reflections).

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;
Natalie Polishuk
  • 183
  • 1
  • 12