How to return a specific status code and no contents from Controller?

C#asp.net Coreasp.net Core-Mvcasp.net Core-Webapi

C# Problem Overview


I want the example controller below to return a status code 418 with no contents. Setting the status code is easy enough but then it seems like there is something that needs to be done to signal the end of the request. In MVC prior to ASP.NET Core or in WebForms that might be a call to Response.End() but how does it work in ASP.NET Core where Response.End does not exist?

public class ExampleController : Controller
{
    [HttpGet][Route("/example/main")]
    public IActionResult Main()
    {
        this.HttpContext.Response.StatusCode = 418; // I'm a teapot
        // How to end the request?
        // I don't actually want to return a view but perhaps the next
        // line is required anyway?
        return View();   
    }
}

C# Solutions


Solution 1 - C#

> this.HttpContext.Response.StatusCode = 418; // I'm a teapot

> How to end the request?

Try other solution, just:

return StatusCode(418);


You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ← Http status code 200
  • return Created() ← Http status code 201
  • return NoContent(); ← Http status code 204

Client Error:

  • return BadRequest(); ← Http status code 400
  • return Unauthorized(); ← Http status code 401
  • return NotFound(); ← Http status code 404


More details:

Solution 2 - C#

The best way to do it is:

return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");

StatusCodes has every kind of return status and you can see all of them here.

Once you choose your StatusCode, return it with a message.

Solution 3 - C#

Look at how the current Object Results are created. Here is the BadRequestObjectResult. Just an extension of the ObjectResult with a value and StatusCode.

https://github.com/aspnet/Mvc/blob/master/src/Microsoft.AspNetCore.Mvc.Core/BadRequestObjectResult.cs

I created a TimeoutExceptionObjectResult just the same way for 408.

/// <summary>
/// An <see cref="ObjectResult"/> that when executed will produce a Request Timeout (408) response.
/// </summary>
[DefaultStatusCode(DefaultStatusCode)]
public class TimeoutExceptionObjectResult : ObjectResult
{
    private const int DefaultStatusCode = StatusCodes.Status408RequestTimeout;

    /// <summary>
    /// Creates a new <see cref="TimeoutExceptionObjectResult"/> instance.
    /// </summary>
    /// <param name="error">Contains the errors to be returned to the client.</param>
    public TimeoutExceptionObjectResult(object error)
        : base(error)
    {
        StatusCode = DefaultStatusCode;
    }
}

Client:

if (ex is TimeoutException)
{
    return new TimeoutExceptionObjectResult("The request timed out.");
}

Solution 4 - C#

This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);

Solution 5 - C#

If anyone wants to do this with a IHttpActionResult may be in a Web API project, Below might be helpful.

// GET: api/Default/
public IHttpActionResult Get()
{
    //return Ok();//200
    //return StatusCode(HttpStatusCode.Accepted);//202
    //return BadRequest();//400
    //return InternalServerError();//500
    //return Unauthorized();//401
    return Ok();
}

Solution 6 - C#

For .Net 5 or .Net 6 based API (Could work in .Net Core 3x as well, didn't checked)

public async Task<ActionResult<List<DocumentsResponseDto>>> SaveDocumentDetails([FromBody] List<DocumentDetailsRequestDto> documentDetailsRequestDto)
{

 var response = await _documentService.SaveDocumentDetails(documentDetailsRequestDto);

 return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status207MultiStatus, response); 
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRonCView Question on Stackoverflow
Solution 1 - C#Lukasz MkView Answer on Stackoverflow
Solution 2 - C#Gabriel ArrudaView Answer on Stackoverflow
Solution 3 - C#sac80644View Answer on Stackoverflow
Solution 4 - C#sobelitoView Answer on Stackoverflow
Solution 5 - C#PAVITRAView Answer on Stackoverflow
Solution 6 - C#KushalSethView Answer on Stackoverflow