[c#] How to return a specific status code and no contents from Controller?

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

The answer is


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.

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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-core

dotnet ef not found in .NET Core 3 How to use Bootstrap 4 in ASP.NET Core ASP.NET Core - Swashbuckle not creating swagger.json file Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 EF Core add-migration Build Failed ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

Examples related to asp.net-core-mvc

Getting value from appsettings.json in .net core Unable to create migrations after upgrading to ASP.NET Core 2.0 ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response ASP.NET Core Get Json Array using IConfiguration ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate How do I access Configuration in any class in ASP.NET Core? How to register multiple implementations of the same interface in Asp.Net Core? ASP.NET Core Identity - get current user How to get current url in view in asp.net core 1.0 How to return HTTP 500 from ASP.NET Core RC2 Web Api?

Examples related to asp.net-core-webapi

Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code RS256 vs HS256: What's the difference? How to return a specific status code and no contents from Controller?