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

痴心易碎 提交于 2019-12-12 06:47:53

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/44462000/removing-from-angular-js-urls-in-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!