How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

后端 未结 7 2195
春和景丽
春和景丽 2020-11-22 12:12

I have the AngularJS seed project and I\'ve added

$locationProvider.html5Mode(true).hashPrefix(\'!\');

to the app.js file. I want to confi

7条回答
  •  臣服心动
    2020-11-22 12:26

    The easiest way I found is just to redirect the requests that trigger 404 to the client. This is done by adding an hashtag even when $locationProvider.html5Mode(true) is set.

    This trick works for environments with more Web Application on the same Web Site and requiring URL integrity constraints (E.G. external authentication). Here is step by step how to do

    index.html

    Set the element properly

    
    

    web.config

    First redirect 404 to a custom page, for example "Home/Error"

    
        
            
        
    
    

    Home controller

    Implement a simple ActionResult to "translate" input in a clientside route.

    public ActionResult Error(string aspxerrorpath) {
        return this.Redirect("~/#/" + aspxerrorpath);
    }
    

    This is the simplest way.


    It is possible (advisable?) to enhance the Error function with some improved logic to redirect 404 to client only when url is valid and let the 404 trigger normally when nothing will be found on client. Let's say you have these angular routes

    .when("/", {
        templateUrl: "Base/Home",
        controller: "controllerHome"
    })
    .when("/New", {
        templateUrl: "Base/New",
        controller: "controllerNew"
    })
    .when("/Show/:title", {
        templateUrl: "Base/Show",
        controller: "controllerShow"
    })
    

    It makes sense to redirect URL to client only when it start with "/New" or "/Show/"

    public ActionResult Error(string aspxerrorpath) {
        // get clientside route path
        string clientPath = aspxerrorpath.Substring(Request.ApplicationPath.Length);
    
        // create a set of valid clientside path
        string[] validPaths = { "/New", "/Show/" };
    
        // check if clientPath is valid and redirect properly
        foreach (string validPath in validPaths) {
            if (clientPath.StartsWith(validPath)) {
                return this.Redirect("~/#/" + clientPath);
            }
        }
    
        return new HttpNotFoundResult();
    }
    

    This is just an example of improved logic, of course every web application has different needs

提交回复
热议问题