感谢Matt DeKrey的建议,我使用两件中间件来完成这项工作。
对于自定义404错误页面,我用:
public class CustomErrorMiddleware
{
private readonly RequestDelegate next;
public CustomErrorMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync("/errors/404.html");
}
}
虽然URL重写我用:
public class UrlRewriteMiddleware
{
private readonly RequestDelegate next;
public UrlRewriteMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
// Redirect from /some/page.htm to /some/page
Regex r1 = new Regex("^/some/[a-zA-Z0-9]+\\.htm$");
if (r1.IsMatch(context.Request.Path.Value))
{
context.Response.Redirect(context.Request.Path.Value.Substring(0, context.Request.Path.Value.Length - 4));
return;
}
// Rewrite from /some/page to /some/page.htm
Regex r2 = new Regex("^/some/[a-zA-Z0-9]+$");
if (r2.IsMatch(context.Request.Path.Value))
context.Request.Path = new PathString(context.Request.Path.Value + ".htm");
await next(context);
}
}
然后Startup.cs
修改为使用每一种。中间件按照指定的顺序运行,所以需要先重新编写URL以修改接收到的请求。自定义404错误中间件需要最后才能捕获任何其他中间件未处理的请求。例如:
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<UrlRewriteMiddleware>();
app.UseStaticFiles();
app.UseMvc();
app.UseMiddleware<CustomErrorMiddleware>();
}
对于您的两个问题,我强烈建议从“IApplicationBuilder”中查找“ASP.NET 5中间件”和“运行”选项。没有一种方法可以满足您要求的任何选项(就像节点连接服务器一样),但如果样本是单独的问题,则可以提供样本。 –