gpt4 book ai didi

c# - ActionResult 未按预期工作

转载 作者:太空狗 更新时间:2023-10-29 23:05:00 25 4
gpt4 key购买 nike

我正在使用 ASP.NET Core 2.1 ActionResult 从 Controller 返回一个文件:

[HttpGet]
public ActionResult<FileResult> Download()
{
var someBinaryFile = "somebinaryfilepath";
return File(new FileStream(firstExe, FileMode.Open, FileAccess.Read, FileShare.Read), System.Net.Mime.MediaTypeNames.Application.Octet, true);
}

但它返回不完整的 json 而不是开始文件下载:

{"fileStream":{"handle":{"value":2676},"canRead":true,"canWrite":false,"safeFileHandle":
{"isInvalid":false,"isClosed":false},"name":"somebinaryfilepath","isAsync":false,"length":952320,"position":0,"canSeek":true,"canTimeout":false

Chrome 开发工具将请求状态指示为“(失败)”,工具提示为“net::ERR_SPDY_PROTOCOL_ERROR”

如果我更改代码使其返回 FileContentResult,然后状态变为“200 ok”,但仍然写入 json 而不是文件下载:

{"fileContents": "somebinaryfilecontent","contentType":"application/octet-stream","fileDownloadName":"","lastModified":null,"entityTag":null,"enableRangeProcessing":true}

如果我将方法签名更改为

public FileResult Download()

或到

public IActionResult Download()

然后文件下载从两个 FileResult 实现开始。

如何使用 ActionResult 下载文件?我是不是遗漏了什么,或者真的是某种错误?

最佳答案

使用 ActionResult<T> 时, T在这种情况下是 specific type你想回来。默认情况下,当直接或使用 ActionResult<T> 从操作返回时,这种类型被序列化为 JSON,正如您在问题中所展示的那样。

对于您的示例,如果您根本不返回特定类型,您需要使用 IActionResult (如您所见,根据您的问题),像这样:

[HttpGet]
public IActionResult Download()
{
...
}

你也可以使用 ActionResult , FileResultFileStreamResult ,但是IActionResult是首选。


这是对为什么的解释,我认为这首先发生了。

ActionResult<T>包含两个隐式运算符:

public static implicit operator ActionResult<TValue>(TValue value)
{
return new ActionResult<TValue>(value);
}

public static implicit operator ActionResult<TValue>(ActionResult result)
{
return new ActionResult<TValue>(result);
}

在您的示例中,返回 FileStreamResult 时, 这两个隐式运算符都可以使用。一个对任何 类型 ( TValue ) 进行操作,另一个对 ActionResult 进行操作.我希望 C# 编译器选择第一个版本,因为 TValue ( FileResult ) 是 FileStreamResult更好匹配项(您的实际返回值)。

这包含在 C# spec 中在“11.5.4 用户定义的隐式转换”部分下。具体来说,我认为适用的是这个描述(我不是这里的专家):

Find the most-specific source type, SX, of the operators in U:

  • If S exists and any of the operators in U convert from S, then SX is S.
  • Otherwise, SX is the most-encompassed type in the combined set of source types of the operators in U. If exactly one most-encompassed type cannot be found, then the conversion is ambiguous and a compile-time error occurs.

在这种情况下,FileResult最具体的源类型(它比 ActionResult 更具体)。

关于c# - ActionResult<FileResult> 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52474276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com