简体   繁体   English

将自定义 HttpResponseMessage 作为 IActionResult 返回

[英]Returning custom HttpResponseMessage as IActionResult

I have a web api which returns IActionResult .我有一个 web api 返回IActionResult

I return FileContentResult from this api like this我像这样从这个 api 返回FileContentResult

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.我有一个要求,我现在想自己控制StatusCode ,而不是FileContentResult自己决定。

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.基本上我想返回我自己设计的HttpResponseMessage ,我可以在其中自己设置标题和其他内容。

But I don't find any way to do this for IActionResult type.但是对于IActionResult类型,我没有找到任何方法。

The only thing that I thought could work is to use ResponseMessageResult something like this我认为唯一可行的方法是使用类似这样的ResponseMessageResult

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.但它的响应与 HttpResponse 不同,它只返回 json 结果和HttpResponseMessage object 详细信息,但实际上并没有返回 Http 响应,考虑到内容类型等,我可以在哪里下载文件。

It gives result like this它给出了这样的结果

在此处输入图像描述

Is there any way I can return my designed file result type http response?有什么方法可以返回我设计的文件结果类型 http 响应?

Legacy ASP.NET Core web API had special handling for raw HttpResponseMessage instances.旧版 ASP.NET 核心 web API 对原始HttpResponseMessage实例进行了特殊处理。 ASP.NET Core does not - your controller action has to return an instance of IActionResult . ASP.NET 核心没有 - 您的 controller 操作必须返回IActionResult的实例。

In your case, I would suggest subclassing FileContentResult and manipulating the status code, then returning your subclass from your controller.在您的情况下,我建议FileContentResult进行子类化并操作状态代码,然后从 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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