How to return a specific status code and no contents from Controller?
Solution 1
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:
- ControllerBase Class (Thanks @Technetium)
- StatusCodes.cs (consts aviable in ASP.NET Core)
- HTTP Status Codes on Wiki
- HTTP Status Codes IANA
Solution 2
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
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.");
}
Solution 4
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 5
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);
Related videos on Youtube
RonC
I'm an entrepreneur who does e-commerce consulting including software development primarily with the .NET stack. I've been working with .NET since it was in beta back in 2001 and I started working with ASP.NET Core prior to the release of 1.0. I'm currently working heavily in ASP.NET Core, Vue.js, Jquery, SqlServer and Lucene.NET. I'm as interested in business management and marketing as I am in software development and have been active in these most of my career. I have earned an MBA from the Kenan-Flagler Business School at the University North Carolina Chapel Hill, as well as a Bachelor of Science in Computer Science from the University of Alaska Fairbanks. I love working at the intersection of Business and Technology. I enjoy learning and helping others.
Updated on July 08, 2022Comments
-
RonC almost 2 years
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 whereResponse.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(); } }
-
GeorgiG over 2 yearsThe 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.
-
Paul about 2 yearsSorry, in ASP.NET Core SOAP service this has no HttpContext.
-
Neutrino almost 2 yearsBut 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.