ASP.NET 5 + Angular 2 路由(模板页面未重新加载)

ASP.NET 5 + Angular 2 routing (template page not REloading)

Angular 2 beta 默认使用 html5 路由。 但是,当您转到某个组件并且路由发生变化(例如 http://localhost:5000/aboutus)并且 您 reload/refresh 页面时,不会加载任何内容。

中也提出了该问题。 大多数答案都说如果我们要在 angular 2 中追求 HTML5 路由,那么这个路由问题应该在服务器端处理。更多讨论 here.

我不确定如何使用 asp.net 服务器环境处理这个问题。

任何 angular 2 开发者也使用 asp.net 并遇到这个问题?

PS。我正在使用 ASP.NET 5。我的 Angular 2 条路线正在使用 MVC 路线。

你用过吗:

指令:组件中的 [RouterOutlet, RouterLink]。

您正在寻找的功能是 URL 重写。有两种可能的处理方法。经典的方法是让 IIS 完成工作,如下所述:

如果您不想依赖 IIS,您可以在 ASP.NET 5 中间件中处理它,如我在此处的回答所示:

您需要在 ASP.NET MVC

中使用此路由
app.UseMvc(routes =>
{
     routes.MapRoute("Default", "{*url}",  new { @controller = "App", @action = "Index" });
});

然后您需要使用 basePath 选项设置 SystemJS

您看到的问题与 Angular 客户端路由和 MVC 服务器端路由之间的区别有关。您实际上收到 404 Page Not Found 错误,因为服务器没有该路由的控制器和操作。我怀疑你没有处理错误,这就是为什么它看起来好像什么也没发生。

当您重新加载 http://localhost:5000/aboutus 或者如果您尝试 link 直接从快捷方式或通过在地址栏中输入它 link link ]ing),它向服务器发送请求。 ASP.NET MVC 将尝试解析该路由,在您的情况下,它将尝试加载 aboutusController 和 运行 Index 操作。当然,这不是您想要的,因为您的 aboutus 路由是一个 Angular 组件。

您应该做的是为 ASP.NET MVC 路由器创建一种方法,以将 URL 应该由 Angular 解析回客户端的方法传递给客户端。

在您的 Startup.cs 文件中,在 Configure() 方法中,将 "spa-fallback" 路由添加到现有路由中:

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

    // when the user types in a link handled by client side routing to the address bar 
    // or refreshes the page, that triggers the server routing. The server should pass 
    // that onto the client, so Angular can handle the route
    routes.MapRoute(
        name: "spa-fallback",
        template: "{*url}",
        defaults: new { controller = "Home", action = "Index" }
    );
});

通过创建指向最终加载您的 Angular 应用程序的控制器和视图的包罗万象的路由,这将允许 URL 将服务器无法处理的内容传递到正确路由的客户端。

然后应用@ZOXEXIVO 的解决方案,在您的 _Layout.cshtml 中添加:

<head>
    <base href="/"/>
    .....
</had>

在您的 Startup.cs 中将此添加到 Configure 方法。这必须在其他 app 语句之前。

app.Use(async (context, next) => {
    await next();

    if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) {
        context.Request.Path = "/index.html"; // Put your Angular root page here 
        await next();
    }
});

我最喜欢的解决方案是将以下代码添加到 Global.asax.cs,它非常顺利可靠地解决了这个问题:

     private const string RootUrl = "~/Home/Index";
     // You can replace "~Home/Index" with whatever holds your app selector (<my-app></my-app>)
     // such as RootUrl="index.html" or any controller action or browsable route

     protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            // Gets incoming request path
            var path = Request.Url.AbsolutePath;

            // To allow access to api via url during testing (if you're using api controllers) - you may want to remove this in production unless you wish to grant direct access to api calls from client...
            var isApi = path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase);
            // To allow access to my .net MVCController for login
            var isAccount = path.StartsWith("/account", StringComparison.InvariantCultureIgnoreCase);
            if (isApi || isAccount)
            {
                return;
            }

            // Redirects to the RootUrl you specified above if the server can't find anything else
            if (!System.IO.File.Exists(Context.Server.MapPath(path)))
                Context.RewritePath(RootUrl);
        }

你可以同时使用路由 当您从 angular 路由调用 Home/Index 时。

Home/Index.cshtml
<my-app></my-app>

app.routing.ts
    const routes: Routes = [
        { path: '', redirectTo: '/Home/Index', pathMatch: 'full' },
        { path: 'Home/Index', component: DashboardComponent }
    ]

所以当 URL 将是 Home/Index 将加载活动 url 的组件,因此它将加载仪表板组件。

这里还有两个选项可以解决这个问题。您可以将哈希位置策略添加到您的应用程序模块。

import { LocationStrategy, HashLocationStrategy } from '@angular/common';

@NgModule({
imports: [.... ],
declarations: [...],
bootstrap: [AppComponent],
providers: [
{
  provide: LocationStrategy,
  useClass: HashLocationStrategy
}
]
})
export class AppModule { }

此选项仅适用于 Angular2 应用程序中位于主页 ASP 控制器

上的部分

您的第二个选择是将路由添加到您的 ASP 控制器,以匹配您的 Angular 2 个应用程序路由和 return "Index" 视图

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [ActionName("Angular-Route1")]
    public IActionResult AngularRoute1()
    {
        return View("Index");
    }

    public IActionResult Route2()
    {
        return View("Index");
    }
}

我运气不好

 routes.MapRoute("Default", "{*url}",  
                  new { @controller = "App", @action = "RedirectIndex" });

上班。我仍然会收到任何客户端路由的 404。

Update:
Figured out why the catch-all route wasn't working: I had an attribute route defined ([Route("api/RedirectIndex")]) and while the plain route can be directly accessed with the fallback route it didn't fire. Removing the attribute route made it work.

另一个似乎与包罗万象的路由处理程序一样简单的解决方案是创建一个自定义处理程序,该处理程序在 Configure():

中的中间件管道结束时触发
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

});

//handle client side routes
app.Run( async (context) =>
{
        context.Response.ContentType = "text/html";
        await context.Response.SendFileAsync(Path.Combine(env.WebRootPath,"index.html"));

});

如果没有其他处理程序接收请求,这基本上最终成为简单地通过现有 URL 请求发送 index.html 的包罗万象的路由。

即使与 IIS Rewrite rules 结合使用也能很好地工作(在这种情况下,上面的代码永远不会被解雇。

写了一篇关于这个主题的博客post:

上面选择的解决方案对我不起作用我在关注了对 T 的所有评论后也得到了 404。我在 MVC5 应用程序中使用 angular5 应用程序。我使用默认索引登录页面作为 angular5 的开始。我的 angular 应用程序位于名为 mvcroot/ClientApp/ 的文件夹中,但在 ng build 上,它通过更改 .angular-[=20 中的一个设置将分发的文件放在 mvcroot/Dist/ 中=] 文件 "outDir": "../Dist"

这个解决方案确实有效。

这样只有 Dist 目录中的路由才会失败。现在,您每次都可以点击刷新,并在保持正确组件的情况下重新加载 angular5 次应用程序的确切路径。一定要先抓住一切。附带说明一下,如果在 angular5 中使用令牌身份验证,请将令牌保存到 window.localStorage(或 angular5 应用程序之外的其他机制),因为点击刷新会清除所有内容您可能将令牌存储在全局变量中的内存。这使用户在刷新时不必再次登录。

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Catch All",
                "dist/{*url}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional });

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }


            );