Return Custom HTTP Status Code from WebAPI 2 endpoint

Solution 1:

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
{
    [RoutePrefix("services/noop")]
    [AllowAnonymous]
    public class NoOpController : ApiController
    {
        [Route]
        [HttpGet]
        public IHttpActionResult GetNoop()
        {
            return new System.Web.Http.Results.ResponseMessageResult(
                Request.CreateErrorResponse(
                    (HttpStatusCode)422,
                    new HttpError("Something goes wrong")
                )
            );
        }
    }
}

Solution 2:

 return Content((HttpStatusCode) 422, whatEver);

credit is for: Return content with IHttpActionResult for non-OK response

and your code must be <= 999

and please ignore codes between 100 to 200.

Solution 3:

I use this way simple and elegant.

public ActionResult Validate(User user)
{
     return new HttpStatusCodeResult((HttpStatusCode)500, 
               "My custom internal server error.");
}

Then angular controller.

function errorCallBack(response) {            
$scope.response = {
   code: response.status,
   text: response.statusText
}});    

Hope it helps you.

Solution 4:

Another simplified example:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        HttpStatusCode codeNotDefined = (HttpStatusCode)422;
        return Content(codeNotDefined, "message to be sent in response body");
    }
}

Content is a virtual method defined in abstract class ApiController, the base of the controller. See the declaration as below:

protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value);