Denis Gladkiy
Denis Gladkiy

Reputation: 2174

How to send 400 HTTP code with binary content form ASP.NET Core's controller?

How to send 400 (or 500) HTTP code with binary content from ASP.NET Core's controller without implementing the IActionResult interface from the ground? Seems like ControllerBase.StatusCode can do the thing, but I can't figure out what the second argument should be.

Upvotes: 0

Views: 174

Answers (1)

Christian Sparre
Christian Sparre

Reputation: 965

You do not need to implement IActionResult, you can set the status code, headers and body content manually in your controller. This should work.

[HttpGet("bin")]
public async Task Data()
{
    var data = Encoding.UTF8.GetBytes("Hello world");
    Response.Headers.Add(new KeyValuePair<string, StringValues>("Content-Type", "application/octet-stream"));
    Response.StatusCode = 400;
    await Response.Body.WriteAsync(data, 0, data.Length);
}

Upvotes: 1

Related Questions