Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show the status code with custom message in c#?

In MVC5, I have used the below code to return the status code with a custom message. It shows the provided message in my output.

return new HttpStatusCodeResult(403, "Not allowed"); 

In .net core framework, above method is not applicable, so I tried the below method but I didn't find how to pass the custom message.

StatusCode(403)  

It shows the default message as "Forbidden"

How can I provide the custom message in StatusCode? Are any other methods available?

like image 580
Karthik Ravichandran Avatar asked Oct 11 '17 13:10

Karthik Ravichandran


2 Answers

I looked into the implementation of standard method (thanks to the Resharper's decompiler):

return Ok("Message"); 

It basically creates new OkObjectResult, providing the value ("Message") to its constructor, and returns that object. In its turn, OkObjectResult is just a derivative from ObjectResult, it has it's own field with default status code (200), retranslates put into its constructor argument (message, or whatever the object you gave) to base constructor (ObjectResult), and assigns value from it's private constant field to base class's property StatusCode, so it's basically kind of a wrapper for ObjectResult.

So, what is the conclusion one can make from all of this: we can return status code with the message in similar fashion using base ObjectResult class:

return new ObjectResult("Your message") {StatusCode = 403}; 
like image 54
Tims Avatar answered Sep 21 '22 22:09

Tims


I found ContentResult to give the most simple and usable results:

private static ActionResult Result(HttpStatusCode statusCode, string reason) => new ContentResult {     StatusCode = (int)statusCode,     Content = $"Status Code: {(int)statusCode}; {statusCode}; {reason}",     ContentType = "text/plain", }; 

Use it by simply returning that call:

return Result(HttpStatusCode.Unauthorized, "Invalid token"); 

This will result in a 401 with the text Status Code: 401; Unauthorized; Invalid token.

like image 45
Mikkel R. Lund Avatar answered Sep 19 '22 22:09

Mikkel R. Lund