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();
}
}
This question is related to
c#
asp.net-core
asp.net-core-mvc
asp.net-core-webapi
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);
Look at how the current Object Results are created. Here is the BadRequestObjectResult. Just an extension of the ObjectResult with a value and StatusCode.
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.");
}
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 in this link https://httpstatuses.com/
Once you choose your StatusCode, return it with a message.
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();
}
Source: Stackoverflow.com