How to return HTTP 429?

C#HttpWcfHttp Status-Code-429

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

If you are hosting the WCF service with IIS you can turn on ASP.Net Compatibility Mode. With that done you can set the status of HttpContext.Current.Response.StatusCode to 429.

With that said. I think your best bet is to try casting the 429 to HttpStatusCode and seeing what happens. If that works then you can save yourself the headache.

Solution 3 - C#

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.

Solution 4 - C#

You can use HttpStatusCode directly

HttpStatusCode.TooManyRequests

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLiathView Question on Stackoverflow
Solution 1 - C#Derek WView Answer on Stackoverflow
Solution 2 - C#JoshView Answer on Stackoverflow
Solution 3 - C#diegocl02View Answer on Stackoverflow
Solution 4 - C#TeepiView Answer on Stackoverflow