混合 SPA 和 ASP.NET MVC 路由

Ben*_*erg 6 c# asp.net-mvc asp.net-core-mvc asp.net-core angular

我正在研究混合路由 Angular 2 和 ASP.NET Core 2(razor)项目。您将如何跳出角度路由并获得剃刀页面?我尝试使用 angular 路由捕获所有未知路由并重新加载未知路由,但是如果有路由 ASP.NET 并且 angular 无法识别它进入循环。类的Configure方法Startup包含这个。

public void Configure(IApplicationBuilder app)
{
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "Index",
            defaults: new { controller = "controller", action = "Index" },
            template: "{controller}");

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

        routes.MapRoute(
            name: "Login",
            defaults: new { controller = "Sessions", action = "New" },
            template: "Login");
    });

    app.UseSpa(spa =>
    {
        // To learn more about options for serving an Angular SPA from ASP.NET Core,
        // see https://go.microsoft.com/fwlink/?linkid=864501

        spa.Options.SourcePath = "ClientApp";
    });
}
Run Code Online (Sandbox Code Playgroud)

一些例子:

  • MVC路线 Mysite.com/documents/view/
  • 角度路线 Mysite.com/PendingTransactions

Zzz*_*Zzz 1

解决方案适用于 MVC 4。

注意:您应该将默认路由放在所有其他路由之后、catch all 路由之前。

从 MVC 路由中排除 Angular 应用程序(您会注意到 true/false 评估有些有趣,这是因为除非我们位于 /app 角度应用程序中,否则应用程序路由由 MVC 处理。您可以在此处看到相反的植入

routes.MapRouteLowercase(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                constraints: new
                {
                    serverRoute = new ServerRouteConstraint(url =>
                    {
                        var isAngularApp = false;
                        if (url.PathAndQuery.StartsWith("/app",
                            StringComparison.InvariantCultureIgnoreCase))
                        {
                            isAngularApp = true;
                        }               
                        return !isAngularApp;
                    })
                }
            );
Run Code Online (Sandbox Code Playgroud)

ServerRouteConstraint 类:

 public class ServerRouteConstraint : IRouteConstraint
    {
        private readonly Func<Uri, bool> _predicate;

        public ServerRouteConstraint(Func<Uri, bool> predicate)
        {
            this._predicate = predicate;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName,
            RouteValueDictionary values, RouteDirection routeDirection)
        {
            return this._predicate(httpContext.Request.Url);
        }
    }
Run Code Online (Sandbox Code Playgroud)

当没有其他路由匹配时,这是一个包罗万象的方法。让 Angular 路由器来处理它

    routes.MapRouteLowercase(
        name: "angular",
        url: "{*url}",
        defaults: new { controller = "App", action = "Index" } // The view that bootstraps Angular 5
    );
Run Code Online (Sandbox Code Playgroud)