How to return HTTP 429?

21,310

Solution 1

From the C# Language Specification 5.0:

The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type.

So this is completely alright to do and would be your best bet:

throw new WebFaultException((System.Net.HttpStatusCode)429);

Solution 2

In case somebody is using the webApi template, in which the controller is returning an IActionResult object.

return new StatusCodeResult(429);

That worked for me.

Share:
21,310
Liath
Author by

Liath

Agile advocate and .NET Development Lead based in the UK

Updated on July 25, 2022

Comments

  • Liath
    Liath almost 2 years

    I'm implementing an API using WCF and the specification says to return HTTP 429 in certain circumstances.

    Normally I'd simply write:

    throw new WebFaultException(HttpStatusCode.NotFound);
    

    However the HttpStatusCode enum does not contain a 429.

    I can obviously cast to the enum

    throw new WebFaultException((HttpStatusCode)429);
    

    However I'm worried that this will not produce the correct result to the application calling my API.

    What's the best way to create extend the HttpStatusCode and send valid (but unsupported) HTTP statuses?

  • Thomas Levesque
    Thomas Levesque over 10 years
    It is alright from a language perspective, but it doesn't mean the API will handle it properly...
  • Derek W
    Derek W over 10 years
    The exception here is being thrown from the API. It is the callers responsibility to handle that exception.
  • John Henckel
    John Henckel about 8 years
    Thanks for this. I wanted to return "Locked" 423. Good to know that casting will work.
  • Liath
    Liath over 4 years
    Hi Teepi - can you add a little more information? Has the enum been updated since I posted the question or is this a different one?
  • Admin
    Admin over 4 years
    This is the actual HttpStatusCode enum
  • Edwin Stoteler
    Edwin Stoteler over 4 years
    does not exist in .net 4.7.2, might want to add what version you are using.
  • Joe Cullinan
    Joe Cullinan almost 4 years
    Framework up to 4.8 doesn't have 429 enumerated, but it's present in .NET Framework 5.0 Preview 7. It was added to Standard and Core in 2.1.
  • Paul Karkoska
    Paul Karkoska almost 4 years
    I can confirm that this type of cast works just fine in .NET Framework 4.8, where "TooManyRequests" is not explicitly defined in the HttpStatusCode enum -- Just in case anyone visiting this post is unclear.
  • Jaans
    Jaans over 3 years
    Today I Learned