.NET 7将文件模式映射到静态文件服务。

huangapple go评论67阅读模式
英文:

.NET 7 map file pattern to static file serving

问题

目前我有普通的方法:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(storageDirectory),
    RequestPath = "/"
});

但我想要更多类似于这样的东西:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(storageDirectory),
    RequestPath = "/[a-b0-9\\-]+/.+"
});

是否有可能以某种方式实现这个需求?

[更新 1]
我可以看到在源代码中,路径是通过 StartsWithSegments 进行检查的:

https://github.com/dotnet/aspnetcore/blob/main/src/Middleware/StaticFiles/src/Helpers.cs

似乎我需要编写一个自定义的中间件?

英文:

I there a way to serve static files with .NET 7 only for certain file patterns?

Currently I have the plain old:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(storageDirectory),
    RequestPath = "/",
});

But I'm looking for something more link

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(storageDirectory),
    RequestPath = "/[a-b0-9\-]+/.+"
});

Is that possible somehow?

[Update 1]
I can see in the source that the path is checked with StartsWithSegments:

https://github.com/dotnet/aspnetcore/blob/main/src/Middleware/StaticFiles/src/Helpers.cs

internal static bool TryMatchPath(HttpContext context, PathString matchUrl, bool forDirectory, out PathString subpath)
{
    var path = context.Request.Path;

    if (forDirectory && !PathEndsInSlash(path))
    {
        path += new PathString("/");
    }

    if (path.StartsWithSegments(matchUrl, out subpath))
    {
        return true;
    }
    return false;
}

Seems like I need to write a custom middleware?

答案1

得分: 2

根据文档:

> RequestPath
> 映射到静态资源的相对请求路径。默认为站点根目录 '/'。

即它只允许指定静态资源所在的文件夹。

您可以尝试的一个选项是通过 UseWhen 分支中间件管道 的选项:

app.UseWhen(ctx => Regex.IsMatch(ctx.Request.Path.Value ?? "", ""), appBuilder =>
    appBuilder.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(storageDirectory),
    }));
英文:

As per docs:

> RequestPath
> The relative request path that maps to static resources. This defaults to the site root '/'.

i.e. it will allow only to specify the folder where static resources are located.

One option you can try is the option to branch the middleware pipeline via UseWhen:

app.UseWhen(ctx => Regex.IsMatch(ctx.Request.Path.Value ?? "", ""), appBuilder =>
    appBuilder.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(storageDirectory),
    }));

huangapple
  • 本文由 发表于 2023年7月24日 20:13:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76754397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定