Garrison Neely Garrison Neely -3 years ago 145
C# Question

Return Custom HTTP Status Code from WebAPI 2 endpoint

I'm working on a service in WebAPI 2, and the endpoint currently returns an

. I'd like to return a status code
, but since it's not in the
enumeration, I'm at a loss as to how it would be sent, since all of the constructors require a parameter of

As it stands now, I'm returning
, but returning a
+ message would be more descriptive and useful for my clients. Any ideas?

Answer Source

According to C# specification:

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

Therefore you can cast status code 422 to HttpStatusCode.

Example controller:

using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CompanyName.Controllers.Api
    public class NoOpController : ApiController
        public IHttpActionResult GetNoop()
            return new System.Web.Http.Results.ResponseMessageResult(
                    new HttpError("Something goes wrong")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download