所以我试图删除#!在我的 Angular 网站中并过渡到 html5。我查看了其他指南,并使用索引文件中的 locationProvider 和 base 实现了它们。当您通过 ng-href 指向链接时,该网站工作正常,但当我按刷新/直接输入 url 时,我收到 404 错误。我读到这与服务器端有关,当 404 被命中时,它不知道要路由到哪里,因为 .otherwise() 是一个 hashbang 函数。
话虽这么说,我查看了 WebApi 配置,发现如果要命中 404,我已经指定了一个默认的routeTemplate,如下所示。
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
如有任何帮助,我们将不胜感激
最佳答案
正如您正确提到的,问题出在服务器端。当您刷新浏览器时,AngularJS 路由不会启动。而是浏览器向服务器发出请求。服务器在所需位置找不到任何内容,因此返回 404。
您在问题中发布的当前服务器端路由仅处理对您的 Web api 的请求。
除了 Web API 路由之外,您还必须添加一个用于提供起始页的 MVC 路由。
假设您的起始页是index.html,将以下路由添加到您的服务器端路由配置
//MVC
RouteTable.Routes.Ignore("api/{*url}"); // ignore api routes for mvc
RouteTable.Routes.MapPageRoute("NonAPIRoute", "{*url}", "~/index.html");
如果您已经安装了 MVC 路由(例如在 App_Start 文件夹中的 RouteConfig 类中),那么您的 RouteConfig 类应该与此类似
using System.Web.Mvc;
using System.Web.Routing;
namespace WebApplication1
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("api/{*pathInfo}"); // ignore api routes
routes.MapPageRoute("NonAPIRoute", "{*url}", "~/index.html");
}
}
}
关于javascript - 删除#!来自 ASP.Net Web API 中的 angular.js URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462000/