Asp.net 5 web api returns status code and body

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?)

+6
source share
3 answers

It works as follows:

 public IActionResult IWillNotBeCalled() { return new UnauthorizedWithMessageResult("MY SQL ERROR"); } public class UnauthorizedWithMessageResult : IActionResult { private readonly string _message; public UnauthorizedWithMessageResult(string message) { _message = message; } public async Task ExecuteResultAsync(ActionContext context) { // you need to do this before setting the body content context.HttpContext.Response.StatusCode = 403; var myByteArray = Encoding.UTF8.GetBytes(_message); await context.HttpContext.Response.Body.WriteAsync(myByteArray, 0, myByteArray.Length); await context.HttpContext.Response.Body.FlushAsync(); } } 

You must set the StatusCode before setting the body, and you must clear the body stream to ensure that the content will be set inside the response.

enter image description here

Hope this helps :)

+4
source

You can do it:

 return new ObjectResult("The message") { StatusCode = (int?) HttpStatusCode.Unauthorized }; 
+1
source

You can return any status code you want, for example:

 return new HttpStatusCodeResult(403); 
0
source

All Articles