2

I have a web api which returns IActionResult.

I return FileContentResult from this api like this

return new FileContentResult(model.Content, ContentType)
{
    EnableRangeProcessing = true
};

I have a requirement in which I now want to control StatusCode myself, rather than FileContentResult decide itself.

I don't find any way to do this.

Basically I want to return my own designed HttpResponseMessage in which I can set headers and other stuff myself.

But I don't find any way to do this for IActionResult type.

The only thing that I thought could work is to use ResponseMessageResult something like this

var content = new ByteArrayContent(bytesWithValidationData);
var response = new HttpResponseMessage();
response.Content = content;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.StatusCode = HttpStatusCode.PartialContent;
response.Content.Headers.ContentRange = new ContentRangeHeaderValue(from, to);

return new ResponseMessageResult(response);

But its response is not same as HttpResponse, it just returns json result with HttpResponseMessage object details but does not actually return Http response considering content type etc. where I can download the file.

It gives result like this

enter image description here

Is there any way I can return my designed file result type http response?

Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105

1 Answers1

2

Legacy ASP.NET Core web API had special handling for raw HttpResponseMessage instances. ASP.NET Core does not - your controller action has to return an instance of IActionResult.

In your case, I would suggest subclassing FileContentResult and manipulating the status code, then returning your subclass from your controller. Something like the following:

public class MyFileContentResult : FileContentResult
{
    public override Task ExecuteResultAsync(ActionContext context)
    {
        context.HttpContext.Response.StatusCode = <your status code>;

        var result = base.ExecuteResultAsync(context);

        return result;
    }
}
Ashwin Pandey
  • 125
  • 13
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
  • Getting this error at the line where the status is getting set :( `System.InvalidOperationException: 'StatusCode cannot be set because the response has already started.' ` – Pawan Nogariya May 27 '20 at 15:03
  • It worked when I moved line `context.HttpContext.Response.StatusCode = ;` above line `var result = base.ExecuteResultAsync(context);` :) In short now the response is getting started after assigning the new status code – Pawan Nogariya May 27 '20 at 15:33
  • Please edit your answer and I will mark it as correct answer – Pawan Nogariya May 28 '20 at 05:34