Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ObjectResult for Status 500

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?

like image 616
steve238 Avatar asked Nov 15 '25 09:11

steve238


2 Answers

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.

like image 55
Sybren S Avatar answered Nov 17 '25 06:11

Sybren S


try

return StatusCode(500, new { Message = "Internal Error." });

to create your own status code.

Link to HTTP status codes

like image 24
big boy Avatar answered Nov 17 '25 07:11

big boy