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?
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};
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With