c# - ASP.NET Core 2.2 防止对文档/文件的直接 URL 访问

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

我有一堆文件存储在一个目录中。这些文件的链接存储在数据库中,如

https://localhost:44325/Repositories/Aopdio/2019/05/QWNjb3VX0FNT1NUSElSRF9LTA==.pdf

当我登录到我的应用程序时,我可以通过该应用程序访问文件。但是,当我复制此链接并将其粘贴到另一个浏览器中时,该文件仍会打开。

有没有办法防止这种情况发生?我希望仅从应用程序提供内容。

这是我的startup.cs

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(RepositoryManager.GetBasePath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))),
    RequestPath = RepositoryManager.GetRequestPath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))
});
app.UseStaticFiles(
    new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Resources")),
        RequestPath = "/Resources"
    }
);

这是我尝试实现的中间件:

在 Startup.cs 中
app.UseRequestMiddleware();

中间件
public class RequestMiddleware
{
    private readonly RequestDelegate next;

    public RequestMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context, Func<Task> next)
    {
        var test = context;
    }
}

调用中间件并在Startup.cs中调用的扩展
public static class RequestMiddlewareExtension
    {
        public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestMiddleware>();
        }
    }
}

但是,我收到此错误:
InvalidOperationException: Unable to resolve service for type 'System.Func`1[System.Threading.Tasks.Task]' while attempting to Invoke middleware 'App.ClassLibrary.Middleware.RequestMiddleware'.

最佳答案

在 app.UseStaticFiles() 的默认配置中,仅提供 wwwroot 下的文件。如果直接提供该目录外的文件,那么您要么已从根文件夹为整个应用程序启用静态文件,要么已在 IIS 上启用目录浏览。您可以检查和禁用它们。

[更新]
当您使用 UseStaticFiles() 提供文件时,请求不方法不会通过正常的中间件管道来。所以你不能拥有像 Authenticate/Authorize 这样的常规中间件功能。您可以拥有一个返回 FileResult 的存储库 Controller ,或者您可以拥有一个自定义中间件,例如 the one here .

关于c# - ASP.NET Core 2.2 防止对文档/文件的直接 URL 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56333992/

相关文章:

URL 中的 ASP.NET 空格或 %20

c# - 在 C# 中使用 Delphi DLL

c# - String.Format 的反转?

c# - 检测到 RichTextBox 中的粘贴

asp.net-mvc - 未找到或错误构建的路线

javascript - ASP.NET MVC RedirectToAction 在 View 中的 AJAX 发布后不起作用

c# - 第三方 Visual Studio 样式表/CSS 编辑器

asp.net - web.config 文件 "executed"是什么时候?

c# - LDAP 服务器不可用

asp.net - 无法加载DLL 'VSPerf110.dll'