Search code examples
c#asp.net-corehttpresponseactionresultwebapi

Returning custom HttpResponseMessage as IActionResult


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?


Solution

  • 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;
        }
    }