2012-04-29 10 views
5

Desidero assicurarmi che il numero fornito da una persona sia legittimo HttpStatusCode.Come posso verificare se un int è un HttpStatusCode legittimo in .NET?

In un primo momento ho pensato di usare Enum.TryParse(..) o Enum.Parse(..) ma è possibile ottengo un risultato non valido con alcuni dati non corretti forniti ..

ad es.

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, quindi se mi passa in un cattivo rapporto qualità aaa, ottengo l'eccezione System.Argument. Ma quando passo il numero 1 (come testo, non un int) ottengo il valore restituito di 1. Mi sarei aspettato che questo fallisse e lanciasse un'eccezione.

Il passaggio di un valore di 400 fa restituisce l'enumerazione corretta BadRequest.

Qualche idea, gente?

risposta

9

Invece di cercare di analizzare il valore semplicemente ci metodo TestDefinito

Enum.IsDefined(typeof(HttpStatusCode),value) 

Il motivo per cui il caso di "1" non fallisce è che si può fare aritmetica binaria su enumerazioni. Questo è usato molto per le bandiere, quindi i valori non specificatamente nel enum potrebbero essere ancora valori validi

+0

Signore/Signora, sei un gentiluomo/gentiluomo e uno studioso!/mi sussurra Woot^Woot! –

-1

perchè non si controlla se in questo enum:

public enum HttpStatusCode 
{ 
    Accepted = 0xca, 
    Ambiguous = 300, 
    BadGateway = 0x1f6, 
    BadRequest = 400, 
    Conflict = 0x199, 
    Continue = 100, 
    Created = 0xc9, 
    ExpectationFailed = 0x1a1, 
    Forbidden = 0x193, 
    Found = 0x12e, 
    GatewayTimeout = 0x1f8, 
    Gone = 410, 
    HttpVersionNotSupported = 0x1f9, 
    InternalServerError = 500, 
    LengthRequired = 0x19b, 
    MethodNotAllowed = 0x195, 
    Moved = 0x12d, 
    MovedPermanently = 0x12d, 
    MultipleChoices = 300, 
    NoContent = 0xcc, 
    NonAuthoritativeInformation = 0xcb, 
    NotAcceptable = 0x196, 
    NotFound = 0x194, 
    NotImplemented = 0x1f5, 
    NotModified = 0x130, 
    OK = 200, 
    PartialContent = 0xce, 
    PaymentRequired = 0x192, 
    PreconditionFailed = 0x19c, 
    ProxyAuthenticationRequired = 0x197, 
    Redirect = 0x12e, 
    RedirectKeepVerb = 0x133, 
    RedirectMethod = 0x12f, 
    RequestedRangeNotSatisfiable = 0x1a0, 
    RequestEntityTooLarge = 0x19d, 
    RequestTimeout = 0x198, 
    RequestUriTooLong = 0x19e, 
    ResetContent = 0xcd, 
    SeeOther = 0x12f, 
    ServiceUnavailable = 0x1f7, 
    SwitchingProtocols = 0x65, 
    TemporaryRedirect = 0x133, 
    Unauthorized = 0x191, 
    UnsupportedMediaType = 0x19f, 
    Unused = 0x132, 
    UseProxy = 0x131 
} 



var exists= Enum.IsDefined(typeof(HttpStatusCode),myEnumValue) 
+6

Perché non convertire tutti questi numeri esadecimali in decimali? Sembra solo una deliberata offuscazione .. – Funbit

+0

@funbit non l'ho fatto. È dal riflettore –

+0

Anche dopo 4 anni buono a sapersi, grazie :) – Funbit

5

Questo è il documented behaviour:

Se valore è un nome che non corrisponde a un nome costante di enumType, il metodo genera un ArgumentException. Se valore è la rappresentazione stringa di un numero intero che non rappresenta un valore sottostante dell'enumerazione enumType, il metodo restituisce un membro di enumerazione il cui valore sottostante è valore convertito in un tipo integrale. Se questo comportamento non è desiderabile, chiamare il metodo IsDefined per assicurarsi che una particolare rappresentazione di stringa di un intero sia effettivamente un membro di enumType.

+0

Ben trovato. Ho fatto scorrere i documenti a lightspeed e ho perso questo paragrafo * molto * importante. Ben individuato! –

Problemi correlati