Search code examples
c#asp.net-coreasp.net-core-mvc

How to return HTTP 500 from ASP.NET Core RC2 Web Api?


Back in RC1, I would do this:

[HttpPost]
public IActionResult Post([FromBody]string something)
{    
    try{
        // ...
    }
    catch(Exception e)
    {
         return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
    }
}

In RC2, there no longer is HttpStatusCodeResult, and there is nothing I can find that lets me return a 500 type of IActionResult.

Is the approach now entirely different for what I'm asking? Do we no longer try-catch in Controller code? Do we just let the framework throw a generic 500 exception back to the API caller? For development, how can I see the exact exception stack?


Solution

  • From what I can see there are helper methods inside the ControllerBase class. Just use the StatusCode method:

    [HttpPost]
    public IActionResult Post([FromBody] string something)
    {    
        //...
        try
        {
            DoSomething();
        }
        catch(Exception e)
        {
             LogException(e);
             return StatusCode(500);
        }
    }
    

    You may also use the StatusCode(int statusCode, object value) overload which also negotiates the content.