首页 > 解决方案 > 在 ASP.net Web API 中为 Angular 前端设置路由

问题描述

我正在尝试设置我当前的 Web API 以服务于 Angular 6 前端应用程序。

我的 Angular 项目位于 Web API 下的“app”目录中。

我可以很好地导航到基本页面,并且所有前端路由都可以正常工作。

我的开发在: https ://test2.localhost.com/app/

我确实必须将 index.html 中的基本位置设置为base href="/app/"

现在我的问题是直接导航到应用程序的子网址。例如 :

https://test2.localhost.com/app/information/planets

我得到一个 404,这让我相信问题出在 Web API 路由中。

如果我要在https://test2.localhost.com/app/启动 Angular 应用程序,我可以导航到该 url,但不能从浏览器中的冷启动。

我在 web.config 中尝试了几个重写规则,但似乎都失败了,并阻止我导航到https://test2.localhost.com/app

Web API 在 IIS 上运行。

在 nodeJs 上运行前端时,路由工作正常,我可以从冷启动导航到所有子 url。

任何帮助将不胜感激。

标签: asp.netangularasp.net-web-api2

解决方案


假设您也有 MVC 路由,请为您的 route.config 尝试此操作:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            constraints: new
            {
                // Add all routes we need MVC to handle here
                serverRoute = new ServerRouteConstraint(url =>
                {
                    return url.PathAndQuery.StartsWith("/qbo",
                        StringComparison.InvariantCultureIgnoreCase);
                })
            });

        // This is a catch-all for when no other routes matched. Let the Angular 2+ router take care of it
        routes.MapRoute(
            name: "angular",
            url: "{*url}",
            defaults: new { controller = "Home", action = "Index" } // The view that bootstraps Angular 2+
        );
    }

这是路由约束类:

using System;
using System.Web;
using System.Web.Routing;

namespace Web
{
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);
    }
}
}

我已经使用它很长时间了,不知道我可能受到了哪个博客的启发。


推荐阅读