How to return a specific status code and no contents from Controller?
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.
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.");
}
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 200return Created()
← Http status code 201return NoContent();
← Http status code 204
Client Error:
return BadRequest();
← Http status code 400return Unauthorized();
← Http status code 401return NotFound();
← Http status code 404
More details:
- ControllerBase Class (Thanks @Technetium)
- StatusCodes.cs (consts aviable in ASP.NET Core)
- HTTP Status Codes on Wiki
- HTTP Status Codes IANA
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);