重定向URL以在处理之前包含hashbang

时间:2015-03-03 20:23:55

标签: angularjs angular-ui-router hashbang

我需要为外部API提供一个回调网址,但是他们不支持'#'在URL中。这对我们不起作用,因为我们使用的是hashbang模式而不是html5模式。

我们正在使用ui-router在页面之间导航,我想知道如何拦截传入的URL(不包含hashbang)并在处理之前插入一个hashbang,以便用户可以导航到正确的页面。

例如: 如果用户遇到' http://mySite/home'然后我希望能够将它们重定向到' http://mySite/#/home'。

- 编辑 - 在与@Gaiazov交换之后,看起来我可能需要对此浏览器URL进行服务器端重定向(而不是重写)。我怎么用Mvc做这个?

1 个答案:

答案 0 :(得分:0)

从这样的服务器端url重写开始。它会使用包含原始网址的查询参数将所有网址重定向到您的网页。

private const string ROOT_DOCUMENT = "/myapp.html?route=";

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string url = Request.Url.LocalPath;
    if (!System.IO.File.Exists(Context.Server.MapPath(url)))
    {
        Context.RewritePath(ROOT_DOCUMENT + Context.Server.UrlEncode(Request.Url.PathAndQuery));
    }
}

然后,在你的角度应用程序

var app = angular.module('myApp', [
    'ui.router',
])

app.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
  $stateProvider
    .state('table', {
      url: '/{table:products|customers}'
    })
    .state('table.edit', {
      url: '/edit/:id'
    })
    .state('home', {
      url: '/*path',  // special 'catch all route',
      template: "Home"
  });

  var re = /^\?path=(.+)/i;

  $urlRouterProvider.rule(function ($injector, $location) {
    // what this function returns will be set as the $location.url
    var path = window.location.search;
    var matches = path.match(re);
    if (matches) {
      console.log(matches);
      path = matches[1];
      return path; 
    }
  });

  $urlRouterProvider.otherwise('/home'); 
}]);

app.run(['$rootScope', '$state', function($rootScope, $state) {
  $rootScope.$state = $state;
}])
<!DOCTYPE html>
<html>
  <head>
    <script data-require="angular.js@1.4.0-beta.5" data-semver="1.4.0-beta.5" src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script>
    <script data-require="ui-router@0.2.13" data-semver="0.2.13" src="//rawgit.com/angular-ui/ui-router/0.2.13/release/angular-ui-router.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <h1>Hello Plunker!</h1>

    <a href="#/products/edit/5">/products/edit/5</a><br/>
    <a href="#/customers/edit/5">/customers/edit/5</a><br/>
    <a href="#/not-a-table/edit/5">/not-a-table/edit/5</a><br/>

    <a href="?path=/products/edit/5">?path=/products/edit/5</a>
    <div ui-view=""></div>

    <pre>
      <!-- Here's some values to keep an eye on in the sample in order to understand $state and $stateParams -->
      $state = {{$state.current.name}}
      $params = {{$state.params}}
      $stateParams = {{$stateParams}}
      $state full url = {{ $state.$current.url.source }}
    </pre>
  </body>

</html>
相关问题