【问题标题】:ASP.NET Core MVC Rewrite and Default documentASP.NET Core MVC 重写和默认文档
【发布时间】:2017-09-14 15:55:03
【问题描述】:

我正在尝试将 Core MVC Rewrite 设置为:

  • localhost/part被请求时,它以默认的localhost/part/index.html响应
  • localhost/part/[anything] 时,仍以index.html 响应(相同的localhost/part/index.html

这是我现在拥有的:

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseRewriter(new RewriteOptions().AddRewrite("/part(/.*)?$", "index.html", true));

    app.UseIdentity();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

我尝试了不同的设置,但没有运气。这在 ASP.NET Core MVC 中是否可行?

更新

这是某种工作的代码:

    app.UseRewriter(new RewriteOptions().AddRewrite("part(\\/.*)?", "part/index.html", true));

    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseIdentity();
    app.UseMvc(...);

所以现在,当请求 localhost/part/[anything]/[something] 时,它确实服务于 index.html。但它作为localhost/part/[anything]/[something]/index.html 服务,这是Angular 的BASE_HREF 的问题。所以应用程序显示 Loading... 并且没有明显加载任何其他内容。嗯...这需要 Angular 部分的修复。我现在不知道修复。有人吗?

【问题讨论】:

  • 我建议这样的问题可以简单地简化为“查找正则表达式 X”,regex 标签可能会很有帮助。
  • 我实际上认为我的正则表达式是正确的。您提出的解决方案不起作用:(
  • 查看我的更新。
  • 试试这个 app.UseRewriter(new RewriteOptions().AddRewrite("/part", "index.html", true));
  • 没有。它不起作用,也不应该。

标签: asp.net-core asp.net-core-mvc asp.net-mvc-routing


【解决方案1】:

是的,使用正确的正则表达式是可能的:

var options = new RewriteOptions()
    .AddRewrite(@"^part(/)?.*$", "part/index.html", true);
app.UseRewriter(options);

//should be after URL rewrite
app.UseStaticFiles();

附:我不是正则表达式专家,但让我试试吧。

【讨论】:

  • @alvipeo 你确定你可以在没有 UrlRewrite 的任何路径上点击index.html 吗? index.html 位置是什么?
  • localhost/part 是我在 ASP.NET Core MVC 项目中的 Angular 4 应用程序。如果没有重写,我可以转到localhost/part(实际上返回/part/index.html),Angular 应用程序就可以工作了。问题是当我点击localhost/part/users/1时,MVC路由开始处理它,显然我得到404。但我想要的是MVC路由根本不处理/part/[whatever]
  • UseStaticFiles 应该在管道中的UseRewriter 之后才能正确处理静态文件请求。我已经更正了正则表达式并得到了一个完全可行的例子。详情见答案。
  • 不,这也无济于事。
  • @alvipeo 检查中间件是如何在服务器日志中触发的。 RewriteMiddleware 把重写结果放在那里,看看。
【解决方案2】:

怎么样:

app.UseRewriter(new RewriteOptions().AddRewrite("part(.*)", "part/index.html", true));
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc(...);

【讨论】:

  • 不,这也不起作用。这是我的应用程序http://localhost:22246/part/directory/patients/new 的真实链接,我正在努力工作。但建议的解决方案都不起作用。
  • 查看编辑,在 poc 应用中验证了这一点。如果这不起作用,则存在与重写无关的其他问题(问题是前导斜杠)
猜你喜欢
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 2015-10-14
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多