在 ASP.net Web API 中为 Angular 前端设置路由

Setting up Routing in ASP.net Web API for Angular frontend

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

我的angular项目位于WebAPI.'app'目录下。

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

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

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

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

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 上的前端时,路由工作正常,我可以从冷启动导航到所有子 urls。

如有任何帮助,我们将不胜感激。

假设您也有 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+
        );
    }

这是路由限制 class:

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);
    }
}
}

我已经用了很长时间了,不知道是哪个博客启发了我。

我想出来了,不确定它是否是最好的方法,但它有效。

我创建了一个名为 FEController (FrontEndController) 的控制器。

public ActionResult Index()
{
  return File(Server.MapPath("/app/") + "index.html", "text/html");
}

然后在RouteConfig.cs

中添加了地图路线
routes.MapRoute(
   "Angular",
   "{app}/{*pathInfo}",
   new { controller = "FE", action = "Index", id = UrlParameter.Optional }
);

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

已测试并确认有效。