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

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

.NET 7 map file pattern to static file serving

问题

目前我有普通的方法:

  1. app.UseStaticFiles(new StaticFileOptions
  2. {
  3. FileProvider = new PhysicalFileProvider(storageDirectory),
  4. RequestPath = "/"
  5. });

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

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

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

[更新 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:

  1. app.UseStaticFiles(new StaticFileOptions
  2. {
  3. FileProvider = new PhysicalFileProvider(storageDirectory),
  4. RequestPath = "/",
  5. });

But I'm looking for something more link

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

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

  1. internal static bool TryMatchPath(HttpContext context, PathString matchUrl, bool forDirectory, out PathString subpath)
  2. {
  3. var path = context.Request.Path;
  4. if (forDirectory && !PathEndsInSlash(path))
  5. {
  6. path += new PathString("/");
  7. }
  8. if (path.StartsWithSegments(matchUrl, out subpath))
  9. {
  10. return true;
  11. }
  12. return false;
  13. }

Seems like I need to write a custom middleware?

答案1

得分: 2

根据文档:

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

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

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

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

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:

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

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:

确定