2

complete novice at C# reporting in

Lets say I have the following code

HttpResponseMessage response = ...

How would I check if the status code for response is a 403?

The property StatusCode is an object - as opposed to an integer, So I am not quite sure what to do.

AlanSTACK
  • 5,525
  • 3
  • 40
  • 99
  • 6
    The `StatusCode` property is an `enum`. With defined values: https://learn.microsoft.com/en-us/dotnet/api/system.net.httpstatuscode – David Jun 21 '19 at 01:07

1 Answers1

10

You can either use the HttpStatusCode enum or cast the enum to an integer:

if (response.StatusCode == HttpStatusCode.Forbidden)
{
   ...
}

or

if ((int)response.StatusCode == 403)
{
   ...
}
Dan D
  • 2,493
  • 15
  • 23
  • 2
    @AlanSTACK I would like to add that the first one is the preferred way: speaking names which self-document their meaning vs magic numbers. What does 403 even mean? Here it means "Forbidden" - so why not write it out then. – ckuri Jun 21 '19 at 06:13
  • Agree 100%! @ckuri – Dan D Jun 21 '19 at 11:32
  • What about the case of a status code that is not part of the enum? – Carl Jul 19 '23 at 16:57