Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't ASP.NET Core have an InternalServerError()?

The Microsoft.AspNetCore.Mvc.Controller base class doesn't have an equivalent of BadRequest(), Ok(), NoContent(), etc. for returning HTTP 500 status codes.

Why can't we do?

try{
  oops();
}
catch(Excpetion e){
  //some handling
  return InternalServerError(e);
}

I know can do return StatusCode(500);, but we are trying to be more consistent with our HTTP codes and would like to know if there is something more consistent with Ok() for returning a 500 code?

like image 775
Nandun Avatar asked Jun 22 '18 19:06

Nandun


People also ask

How does net core handle errors?

To configure a custom error handling page for the Production environment, call UseExceptionHandler. This exception handling middleware: Catches and logs unhandled exceptions. Re-executes the request in an alternate pipeline using the path indicated.

What is middleware in .NET core?

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.


2 Answers

ASP.NET Core 2.x doesn't have InternalServerError method. Instead you can include the following library.

using Microsoft.AspNetCore.Http;

And then use the following code.

return new StatusCodeResult(StatusCodes.Status500InternalServerError);

Or if you want to add the exception along with the response, try the following code

var result = StatusCode(StatusCodes.Status500InternalServerError, exception);
return result;    
like image 178
Foyzul Karim Avatar answered Oct 20 '22 23:10

Foyzul Karim


If just like me you didn't understand where the StatusCode method is coming from in Karim's answer, this code will work just as well:

var errorObjectResult = new ObjectResult(exceptionMessage);
errorObjectResult.StatusCode = StatusCodes.Status500InternalServerError;
                
return errorObjectResult;
like image 8
Luis Gouveia Avatar answered Oct 21 '22 00:10

Luis Gouveia