gek0n gek0n -4 years ago 363
C# Question

C# how create WebException with Response status code

I make some fake class, that should have same behavior as original one.
Original class sometimes throws WebExceptions (with

in response from server).

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

Answer Source

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. ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download