英文:
.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),
}));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论