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

时间:2018-07-17 09:45:35

标签: c# asp.net-core-webapi

我有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

1 个答案:

答案 0 :(得分:3)

尝试返回一个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,因为它们指示可以从Action中获得什么HTTP状态代码,对于IActionResult,可以返回什么类型(ActionResult<T>为您处理)?


由于这似乎正在访问文件,因此您可能希望将其设置为async Task<ActionResult<FileContentResult>>,并使用await关键字访问文件asynchronously

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");
}
相关问题