I am working on a project using ASP.NET 5 and I am writing a web api.
I have inherited some code and database stored procedures that use raiserror to indicate that something is wrong (wrong username / password, expired license, etc.).
The stored procedure does not return anything to uniquely identify this error, except for the message text.
I want to be able to return an HTTP UNAUTHORIZED response, but also send an error message along with the client.
The built-in IActionResult HttpUnauthorized() method does not allow specifying a reason.
So, I wrote my own ActionResult, which looks like this:
public class UnauthorizedWithMessageResult : IActionResult { private readonly string _message; public UnauthorizedWithMessageResult(string message) { _message = message; } public async Task ExecuteResultAsync(ActionContext context) { using (var sw = new HttpResponseStreamWriter(context.HttpContext.Response.Body, Encoding.UTF8)) { await sw.WriteLineAsync(_message); } await new HttpUnauthorizedResult().ExecuteResultAsync(context); } }
The problem is that the client receives 200-OK, as if everything is in order.
I went through this and after the delegation to the HttpUnauthorizedResult done, the status code is really set to 403.
It seems that the web API (at some point) sees that there is content in the body of the response and decides that everything is in order and resets the status code.
Is there a way around this without having to resort to sending the message as a header or something else? (or is this the right way to do this?)
source share