【发布时间】:2017-08-25 04:44:21
【问题描述】:
我有一个带有一些 mvc 控制器和一个 angular 2 应用程序的 dot net core web 应用程序。我正在尝试将“www.example.com/old/path”之类的请求路径重写为“www.example.com/new/path”,然后将其发送到 angular 2 应用程序(该应用程序的路由设置仅适用于“新/路径”)。但是,即使重写似乎已经奏效(从断点来看),Angular 仍然走上了老路。我怀疑这可能反映了我对中间件执行顺序的理解存在某种差距(但我尝试了不同的顺序,并且到处乱扔重写代码无济于事)。
这就是url重写中间件的样子(UrlRewritingMiddleware.cs):
public sealed class UrlRewritingMiddleware
{
private readonly RequestDelegate _next;
private readonly string OldPathSegment= "/old/path/";
private readonly string NewPathSegment= "/new/path/";
public UrlRewritingMiddleware(RequestDelegate next)
{
this._next = next;
}
private void RewriteUrl(HttpContext context)
{
if (context.Request.Path.Value.IndexOf(OldPathSegment, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
context.Request.Path = new PathString(Regex.Replace(context.Request.Path.Value, OldPathSegment, NewPathSegment, RegexOptions.IgnoreCase));
}
}
public async Task Invoke(HttpContext context)
{
RewriteUrl(context);
await _next.Invoke(context);
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/app/root/index.html";
context.Response.StatusCode = 200;
await _next.Invoke(context);
RewritePathsInContext(context);//spam
}
else
{
//spam
RewritePathsInContext(context);
}
}
}
然后这就是 Startup.cs Configure 方法的样子:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//putting in the beginning, I get error in angular
//EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '/old/path'
app.UseUrlRewritingMiddleware();
app.AnotherCustomMiddleware();//I can see Path changed to new/path inside here
app.UseDefaultFiles();
app.UseMvc();
app.UseStaticFiles();
//putting this at the end gives me 404 in asp.net
//app.UseUrlRewritingMiddleware();
}
【问题讨论】:
标签: c# angular asp.net-core asp.net-core-mvc asp.net-core-middleware