As an alternative to the other answers, you can also use this code if you want to return an IActionResult
within an ASP.NET controller.
ASP.NET
return Content(HttpStatusCode.Unauthorized, "My error message");
Update: ASP.NET Core
Above code does not work in ASP.NET Core, you can use one of these instead:
return StatusCode((int)System.Net.HttpStatusCode.Unauthorized, "My error message");
return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized, "My error message");
return StatusCode(401, "My error message");
Apparently the reason phrase is pretty optional (Can an HTTP response omit the Reason-Phrase?)