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 204Client Error:
return BadRequest();
← Http status code 400return Unauthorized();
← Http status code 401return NotFound();
← Http status code 404
More details:
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 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);
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With