54

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(Exception ex){
  //some handling
  return InternalServerError(ex);
}

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?

3
  • 2
    That is the exact same thing. 500 = internal server error. You could always create a quick extension method if you wanted to. Commented Jun 22, 2018 at 19:26
  • You could always set the response code manually. Response.StatusCode = 500; Commented Jun 22, 2018 at 19:44
  • Related post - How to return HTTP 500 from ASP.NET Core RC2 Web Api? Commented Nov 20, 2021 at 3:00

2 Answers 2

70

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;    
Sign up to request clarification or add additional context in comments.

2 Comments

If for some reason you need to keep api backward compatible with the 'InternalServerError' you could use Microsoft.AspNetCore.Mvc.WebApiCompatShim but the effort of adding the package is more than refactoring your code to the one Foyzul posted. nuget.org/packages/Microsoft.AspNetCore.Mvc.WebApiCompatShim
I don't know if it was the case at the time of the original answer, but the ControllerBase class now has a StatusCode method that returns a StatusCodeResult. So the code can now be: return StatusCode(StatusCodes.Status500InternalServerError);
13

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.