gpt4 book ai didi

c# - 将 FileContentResult 与未经授权的结果一起使用

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:57 25 4
gpt4 key购买 nike

我有 API 端点,当用户被授权访问文件时,它返回 FileContentResult。当用户没有访问权限时,我想返回 Unauthorized/401 错误。

[HttpGet]
[Authorize("FileAccess")]
public FileContentResult GetFile(Guid fileId)
{
if (!this.UserHasNoAccessToFile(fileId))
return Unauthorized(); // does not work

return File(...)

}

看起来,我不能简单地返回 Unauthorized() 而这不能转换为 FileContentResult

最佳答案

尝试返回 ActionResult<T>相反。

[HttpGet]
[Authorize("FileAccess")]
[ProducesResponseType(200)]
[ProducesResponseType(401)]
public ActionResult<FileContentResult> GetFile(Guid fileId)
{
if (!this.UserHasNoAccessToFile(fileId))
return Unauthorized();

return File(...)

}

ActionResult<T> is new to ASP.NET Core 2.1 ,因此您可能需要更新。如果您不想更新,只需返回 IActionResult并将以下属性添加到您的 Action 方法中

[ProducesResponseType(typeof(FileContentResult), 200)]
[ProducesResponseType(401)]

ProducesResponseType ActionResult<T> 上的属性是可选的和 IActionResult .他们是recommended因为它们指示可以从操作中获得哪些 HTTP 状态代码,在 IActionResult 的情况下, 可以返回什么类型( ActionResult<T> 为您处理)


而且由于这似乎是在访问文件,您可能希望将其设为 async Task<ActionResult<FileContentResult>>而是访问文件 asynchronouslyawait关键词

public async Task<ActionResult<FileContentResult>> GetFile(Guid fileId)
{
if (!this.UserHasNoAccessToFile(fileId))
return Unauthorized();

var bytes = await System.IO.File.ReadAllBytesAsync("some path");
return File(bytes, "contentType");
}

关于c# - 将 FileContentResult 与未经授权的结果一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51378175/

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