$location / switching between html5 and hashbang mode / link rewriting

前端 未结 4 1616
情深已故
情深已故 2020-11-22 01:49

I was under the impression that Angular would rewrite URLs that appear in href attributes of anchor tags within tempaltes, such that they would work whether in html5 mode or

4条回答
  •  梦毁少年i
    2020-11-22 02:54

    This took me a while to figure out so this is how I got it working - Angular WebAPI ASP Routing without the # for SEO

    1. add to Index.html - base href="/">
    2. Add $locationProvider.html5Mode(true); to app.config

    3. I needed a certain controller (which was in the home controller) to be ignored for uploading images so I added that rule to RouteConfig

           routes.MapRoute(
              name: "Default2",
              url: "Home/{*.}",
              defaults: new { controller = "Home", action = "SaveImage" }
          );
      
    4. In Global.asax add the following - making sure to ignore api and image upload paths let them function as normal otherwise reroute everything else.

       private const string ROOT_DOCUMENT = "/Index.html";
      
      protected void Application_BeginRequest(Object sender, EventArgs e)
      {
          var path = Request.Url.AbsolutePath;
          var isApi = path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase);
          var isImageUpload = path.StartsWith("/home", StringComparison.InvariantCultureIgnoreCase);
      
          if (isApi || isImageUpload)
              return;
      
          string url = Request.Url.LocalPath;
          if (!System.IO.File.Exists(Context.Server.MapPath(url)))
              Context.RewritePath(ROOT_DOCUMENT);
      }
      
    5. Make sure to use $location.url('/XXX') and not window.location ... to redirect

    6. Reference the CSS files with absolute path

    and not

    
    

    Final note - doing it this way gave me full control and I did not need to do anything to the web config.

    Hope this helps as this took me a while to figure out.

提交回复
热议问题