207

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();   
    }
}

6 Answers 6

383

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:

Sign up to request clarification or add additional context in comments.

4 Comments

The simplicity and virtue of this approach can't be overstated! I had a need to map an HttpResponseMessage and return it from my own endpoint and this was the only comment that was actually helpful.
Sorry, in ASP.NET Core SOAP service this has no HttpContext.
But returning StatusCode(418) does return content. It returns a JSON object containing the status code and a few other properties, so I don't see how this is even a valid answer to the question.
@Neutrino what's returned depends really on your app settings. In some cases (for Api controllers and when not custom data/object returned) .NET Core returns ProblemDetails object - this is a machine-readable format for specifying errors in HTTP API responses based on tools.ietf.org/html/rfc7807
32

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.

1 Comment

Thank you for making me aware of this remarkably useful status code
8

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.");
}

Comments

8

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); 
}

Comments

7

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();
}

1 Comment

Does InternalServerError exist as an IHttpActionResult?
6

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);

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.