[英]Removing #! from angular.js Urls in ASP.Net Web API
因此,我試圖刪除#! 在我的有角網站並過渡到html5。 我看過其他指南,並使用locationProvider和索引文件中的base實施了它們。 當您通過ng-href將其定向到鏈接時,該站點工作正常,但是當我按刷新/直接輸入URL時,出現404錯誤。 我讀到的這與服務器端有關,因為.otherwise()是hashbang函數,因此服務器端不知道在命中404時要路由到哪里。
話雖如此,我查看了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");
}
}
}
將配置添加到項目中以啟用HTML5模式並刪除前綴
.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix(''); // by default '!'
$locationProvider.html5Mode({
enabled: true
});
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.