借助中间件(middleware)可以“篡改”请求上下文信息(这里是Request.Path)的能力解决了这个问题
中间件的实现代码如下:
public class LowercaseUrlMiddleware
{
private readonly RequestDelegate _next;
private readonly IEnumerable _wwwrootDirs;
public LowercaseUrlMiddleware(RequestDelegate next, IEnumerable wwwrootDirs)
{
_wwwrootDirs = wwwrootDirs;
_next = next;
}
public Task Invoke(HttpContext context)
{
var path = context.Request.Path.Value;
if (_wwwrootDirs.Any(dir => path.IndexOf($"/{dir}", StringComparison.OrdinalIgnoreCase) == 0))
{
context.Request.Path = new PathString(context.Request.Path.Value.ToLower());
}
return _next(context);
}
}
Startup.Configure 中添加中间件的代码如下:
var wwwrootDirs = Directory.GetDirectories(env.WebRootPath)
.Select(dir => Path.GetFileName(dir));
app.UseMiddleware(wwwrootDirs);
app.UseStaticFiles();