I wish to make sure that the number a person provides, is a legit HttpStatusCode.
At first I thought of using Enum.TryParse(..)
or Enum.Parse(..)
but it's possible I get an invalid result with some bad data provided..
eg.
In: Enum.Parse(typeof (HttpStatusCode), "1")
Out: 1
In: Enum.Parse(typeof (HttpStatusCode), "400")
Out: BadRequest
In: Enum.Parse(typeof (HttpStatusCode), "aaa")
Out: System.ArgumentException: Requested value 'aaa' was not found.
Ok, so if I pass in a bad aaa value, I get the System.Argument exception. But when I pass in a number 1 (as text, not an int) i get the return value of 1. I would have expected this to fail and throw an exception.
Passing a value of 400 does return the correct BadRequest
enumeration.
Any ideas, folks?
The HttpStatusCode enumeration contains the values of the status codes defined in RFC 2616 for HTTP 1.1. The status of an HTTP request is contained in the HttpWebResponse. StatusCode property. If the HttpWebRequest.
In the main window of the program, enter your website homepage URL and click on the 'Start' button. As soon as crawling is complete, you will have all status codes in the corresponding table column. Pages with the 4xx and 5xx HTTP status codes will be gathered into special issue reports.
Instead of trying to parse the value simply us the IsDefined method
Enum.IsDefined(typeof(HttpStatusCode),value)
The reason why the case with "1" doesn't fail is that you can do binary arithmetic on enumerations. This is used a lot for flags, thus values not specifically in the enum might still be valid values
That is the documented behaviour:
If value is a name that does not correspond to a named constant of enumType, the method throws an ArgumentException. If value is the string representation of an integer that does not represent an underlying value of the enumType enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of enumType.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With