How to return HTTP 429?
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.
Comments
-
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 over 10 yearsIt is alright from a language perspective, but it doesn't mean the API will handle it properly...
-
Derek W over 10 yearsThe exception here is being thrown from the API. It is the callers responsibility to handle that exception.
-
John Henckel about 8 yearsThanks for this. I wanted to return "Locked" 423. Good to know that casting will work.
-
Liath over 4 yearsHi 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 over 4 yearsThis is the actual HttpStatusCode enum
-
Edwin Stoteler over 4 yearsdoes not exist in .net 4.7.2, might want to add what version you are using.
-
Joe Cullinan almost 4 yearsFramework 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 almost 4 yearsI 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 over 3 yearsToday I Learned