In my AspNetCore.Mvc App I want to create a new Status 500 Request Object Result.
For Status Code 400 I can use the following line
new BadRequestObjectResult("Bad Request!");
For Status Code 500 I can achieve it using a JsonResult:
new JsonResult(new {Message = "Internal Error"}) {StatusCode = 500};
Is there a better way to acheive this similar to a BadRequestObjectResult?
Since net core 3.0 and later you can use the Problem ObjectResult.
[HttpPost]
public IActionResult Post([FromBody] string value)
{
try
{
// ...
}
catch (Exception ex)
{
return Problem(
//all parameters are optional:
//detail: "Error while processing posted data."; //an explanation, ex.Stacktrace, ...
//instance: "/city/London" //A reference that identifies the specific occurrence of the problem
//title: "An error occured." //a short title, maybe ex.Message
//statusCode: StatusCodes.Status504GatewayTimeout, //will always return code 500 if not explicitly set
//type: "http://example.com/errors/error-123-details" //a reference to more information
);
}
}
It will return status-code 500 as long as no other status is explicitly set.
try
return StatusCode(500, new { Message = "Internal Error." });
to create your own status code.
Link to HTTP status codes
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