Removing #! from angular.js Urls in ASP.Net Web AP

2019-08-18 03:42发布

So I am trying to remove the #! in my angular site and transition to html5. I've looked at other guides and I've implemented them with the locationProvider and base within the index file. The site works fine when you direct it through ng-href to a link but when I press refresh/directly input the url I get a 404 error. I was reading this has to do with the server side in which it does not know where to route when a 404 is hit since the .otherwise() is a hashbang function.

That being said, I looked at the WebApi config and found I already had directed a default routeTemplate if it were to hit a 404 as shown below.

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

Any help would be appreciated

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-18 04:23

Add a config to your project to enable HTML5 mode and remove prefix

.config(['$locationProvider', function($locationProvider) {
    $locationProvider.hashPrefix(''); // by default '!'
     $locationProvider.html5Mode({
         enabled: true
     });
}]);
查看更多
甜甜的少女心
3楼-- · 2019-08-18 04:31

As you correctly mentioned, the issue lies on the server side. When you refresh your browser, the AngularJS routing doesn't kick in. Instead the browser issues a request to the server. The server doesn't find anything at the desired location, so it returns a 404.

Your current server side route that you posted in your question just handles requests to your web api.

In addition to the web api route you do have to add an mvc route that delivers your start page.

Assuming that your start page is index.html, add the following routing to your server side route config

//MVC
RouteTable.Routes.Ignore("api/{*url}"); // ignore api routes for mvc
RouteTable.Routes.MapPageRoute("NonAPIRoute", "{*url}", "~/index.html");

if you do already have MVC Routing in place (for example in a class RouteConfig in the App_Start folder), then your RouteConfig class should look similar to this

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");
        }
    }
}
查看更多
登录 后发表回答