Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an int is a legit HttpStatusCode in .NET?

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?

like image 578
Pure.Krome Avatar asked Apr 29 '12 06:04

Pure.Krome


People also ask

What is HttpStatusCode in C#?

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.

How do I get HttpStatusCode?

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.


2 Answers

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

like image 51
Rune FS Avatar answered Oct 05 '22 06:10

Rune FS


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.

like image 43
Damien_The_Unbeliever Avatar answered Oct 05 '22 06:10

Damien_The_Unbeliever