简体   繁体   中英

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

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM