Вопрос

I am trying to handle 302 redirect response. I am seeing different behaviour of toString method of HttpStatusCode.

HttpWebResponse response = (HttpWebResponse) _webRequest.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
        throw new TestException(TestException.HttpErrorClass,response.StatusCode.ToString(),"");

The issue is when I debug and look at response Object the StatusCode is shows "FOUND" status. But when I do toString to this code I get "Redirect" String. Also, It does not consistently returns "Redirect" string, It sometimes returns "FOUND" string on my colleague's machine.

Has there been any changes in toString method from .net 4.0 to .net 4.5? Had anyone seen similar issue?

Это было полезно?

Решение

If you look at the definition of HttpStatusCode, you'll find that there is more than one enum member for the value 302. Based on the docs, when there is more than one definition, the resulting string value will not always be the same. Take a look at the GetName method (which is what ToString pretty much does).

http://msdn.microsoft.com/en-us/library/system.enum.getname(v=vs.110).aspx

If multiple enumeration members have the same underlying value, the GetName method guarantees that it will return the name of one of those enumeration members. However, it does not guarantee that it will always return the name of the same enumeration member. As a result, when multiple enumeration members have the same value, your application code should never depend on the method returning a particular member's name.

Take a look at this answer for some more insight: Why is it okay for an enum to have two different names with the same numeric value?

Другие советы

According to Nathan's answer, there a really two entries in the HttpStatusCode-enumeration. See http://referencesource.microsoft.com/#System/net/System/Net/HttpStatusCode.cs#9b95c882b40ef96e

So, depending on the response you are getting wether this string or the other one, but the code is always the same.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top