【问题标题】:Serve static folder with authentication in the asp net core 2.0在 asp net core 2.0 中提供具有身份验证的静态文件夹
【发布时间】:2019-06-11 05:59:37
【问题描述】:

我正在使用带有 MVC 的 asp net core 2.0.5,并希望在wwwroot 之外提供一个静态文件夹。

我的输入文件如下所示。

wwwroot
staticfolder
    10
        index.html
        image1.png
        image2.png
        sub-folder
            image3.jpg

index.html 是由其他程序生成的。所有图像都在 index.html 中使用。

我们希望在检查身份验证后进入服务器,即用户可以通过路径api/flight/10/index.html查看index.html。但我需要检查访问资源flight 10 的用户权限。

我了解Physicalfile 可用于在 wwwroot 之外提供静态文件(例如 *.png),还可以将 app.UseStaticFiles 配置为在 startup.cs 中提供文件夹和文件。

一些伪代码作为最小示例。

[Route("api/flight/{flight}/index.html")]
[HttpGet]
public IActionResult GetImageThumbnail(
    [FromRoute] int flight)
{
    // Check permission
    List<Flight> data = _context
        .Flight(id: flight)
        .ToList();

    if (data.Count() == 0)
    {
        return NotFound("No permission.");
    }

    // data[0].BaseFolder is a folder outside wwwroot
    string filename = data[0].BaseFolder + "/index.html";
    // Return the content for index.html
    ...
}

所以我的问题是我应该如何使用上面类似的方法来服务一个混合了 html 和图像的文件夹。

【问题讨论】:

  • 您是否希望对 wwwroot 中的特定文件夹进行飞行检查?
  • 不,在 wwwroot 文件夹之外
  • 您能否阐明期望的最终结果应该是什么样子?输入是什么,输出是什么。
  • 谢谢。我会尽力澄清我的问题。

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


【解决方案1】:

我找到了一个简单的解决方案来实现我的目标。在这里发帖以防其他人有同样的问题。

关键是使用{*file} 设置路由,它将匹配末尾的任何字符串。

[Route("api/flight/{flight}/{*file}")]
[HttpGet]
public async Task<IActionResult> GetImageThumbnail([FromRoute]int flight, 
    [FromRoute] string file)
{

    // Check permission
    List<Flight> data = _context
    .Flight(id: flight)
    .ToList();

    if (data.Count() == 0)
    {
    return NotFound("No permission.");
    }
    string filename = Path.Combine(data[0].BaseFolder, file);
    var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

    string minetype = "";
    provider.TryGetContentType(filename, out minetype);
    return PhysicalFile(filename, minetype);
}

【讨论】:

  • 你有没有找到其他优雅的方法来实现它?
  • 目前没有其他方法
猜你喜欢
  • 1970-01-01
  • 2018-01-27
  • 2018-03-23
  • 2018-04-04
  • 2021-05-31
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
相关资源
最近更新 更多