代码之家  ›  专栏  ›  技术社区  ›  Velocoder

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

  •  1
  • Velocoder  · 技术社区  · 6 年前

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

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

    看,我不能简单地回来 Unauthorized() 但无法将其转换为 文件内容结果 .

    1 回复  |  直到 6 年前
        1
  •  3
  •   p3tch    6 年前

    尝试返回 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 并将以下属性添加到您的操作方法中

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

    这个 ProducesResponseType 属性是可选的 操作结果<t> 影响结果 . 他们是 recommended 因为它们指示了可以从操作中预期的HTTP状态代码,以及 影响结果 ,可以返回哪些类型( 操作结果<t> 为您处理)


    因为这似乎是在访问文件,所以您可能希望 async Task<ActionResult<FileContentResult>> 而是访问文件 asynchronously await 关键字

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