asp.net - 在 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。
任何帮助将不胜感激。
解决方案
假设您也有 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);
}
}
}
我已经使用它很长时间了,不知道我可能受到了哪个博客的启发。
推荐阅读
- android - Xamarin Android BottomNavigationView 在右侧添加一个空白区域
- long-integer - 使用 RS Logix 500 处理长整数数据文件的最大十进制值是多少?
- colors - wordcloud2 丢弃长词,导致颜色不匹配
- pine-script - 通过 pine 策略更改 TradingView 中图表的时间间隔
- vue.js - How can traslate the default value of the props?
- git - Making sure a fresh git subtree is available everytime
- r - Is there an easier way to find the count of a variable using multiple criterias? R
- sql - PostgreSQL - 如何使用 varchar 参数调用过程
- node.js - Node adding braces to request.body parameter
- node.js - 赋值中的左侧无效 | 不和谐.js