删除#!来自于ASP.Net Web API中的angular.js Urls

时间:2017-06-09 15:50:33

标签: javascript angularjs asp.net-web-api hashbang

所以我想删除#!在我的角度网站和过渡到HTML5。我已经查看了其他指南,并且我已经使用locationProvider和index在索引文件中实现了它们。当你通过ng-href指向链接时,网站工作正常,但是当我按下刷新/直接输入网址时,我收到404错误。我正在阅读这与服务器端有关,因为.otherwise()是一个hashbang函数,当它被命中404时它不知道在哪里路由。

话虽如此,我查看了WebApi配置,发现我已经指示了默认的routeTemplate,如果要点击404,如下所示。

// 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();

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

正如您所正确提到的,问题出在服务器端。刷新浏览器时,AngularJS路由不会启动。而是浏览器向服务器发出请求。服务器在所需位置找不到任何内容,因此返回404。

您在问题中发布的当前服务器端路由只处理对您的网络API的请求。

除了网络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");
        }
    }
}

答案 1 :(得分:0)

为项目添加配置以启用HTML5模式并删除前缀

.config(['$locationProvider', function($locationProvider) {
    $locationProvider.hashPrefix(''); // by default '!'
     $locationProvider.html5Mode({
         enabled: true
     });
}]);