Toxcique
Toxcique

Reputation: 49

How do I return a custom HTTP response in an ASP.NET Core Controller?

In ASP.NET core MVC, how do I return a custom HTTP response, along with a custom HTTP code? I wish to be able to build the response myself, and preferably return it from a controller.

  public IActionResult Index()
    {
          // set custom HTTP response and return
    }

.... someone fetches Index, and I should be able to manually send a response alike below, where I can control every aspect of the response. I can even work with simply returning a string I build myself.

HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed

How do I do this in ASP.NET Core MVC?

Upvotes: 2

Views: 6037

Answers (2)

Mick
Mick

Reputation: 6864

Adapting the answer from here...

public IActionResult Index()
{
    return StatusCode((int)HttpStatusCode.MovedPermanently);
}

Another example if you wanted pass back a 400 status code and validation errors in the response body...

public IActionResult Index()
{
    var validationErrors = _repository.Validate()
    return StatusCode((int)HttpStatusCode.BadRequest, validationErrors);
}

Upvotes: 1

Toxcique
Toxcique

Reputation: 49

I realised I was a bit tunnelvisioned, the answer is much simpler than I at first expected.

        public void Index()
    {
        Response.StatusCode = 200;
        Response.StartAsync();

        return;
    }

This allows one to simply add data to a Response themselves and send them to the client. I am using ASP.NET Core 3.1 MVC.

Upvotes: 0

Related Questions