简体   繁体   中英

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

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

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");
        }
    }
}

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
     });
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM