【问题标题】:How to make base href / IIS virtual directory case insensitive for angular app?如何使基本 href / IIS 虚拟目录对 Angular 应用程序不区分大小写?
【发布时间】:2020-04-06 09:36:46
【问题描述】:

有类似的question没有正确答案。

如果我在 app.module.ts 中设置:

providers: [
  { provide: APP_BASE_HREF, useValue: '/my/app'},

然后输入 localhost:4200/my/app

this.location.path()

返回正确的路径“”。

但是,如果我输入 localhost:4200/my/App

this.location.path()

返回错误的“/my/App”。

出于这个问题之外的原因,我会检查 URL。所以我的问题是:如何使基本 href 不区分大小写?

我假设在 IIS 上安装失败的原因相同。

【问题讨论】:

  • 你用过LowerCaseUrlSerializer吗?
  • 是的。它不影响基本 href
  • 我认为您需要更改 iis 上的一些设置
  • 您可以编写一个 IIS 规则来重定向到应用程序的小写版本。或者,您可以编写一个在运行时提供 APP_BASE_HREF 的工厂,以返回当前在 url 中的值

标签: angular angular-routing angular-router


【解决方案1】:

我认为最好的方法可能是强制 IIS 使用重写规则将用户重定向到my/app。但是我不知道IIS,所以我不能给你一个解决方案。

如果你想用角度来做,你可以使用下面的代码。它通过工厂动态提供APP_BASE_HREF 令牌

export function baseHrefFactory()
{
  let expectedBaseHref = '/my/app';
  let currentBaseHref = window.location.pathname.substr(0, expectedBaseHref.length);
  //Add checks herre if needed
  return currentBaseHref;
}

@NgModule({
/**/
  providers: [
    {provide: APP_BASE_HREF, useFactory: baseHrefFactory}
  ]
})
export class AppModule

【讨论】:

    【解决方案2】:

    我喜欢@David 的回答,但我发现我的网址在部署时以 /my/app/my/app 结尾,我不知道为什么。如果 href 相同但情况不同,我改变了他将用户重定向到正确的基本 href 的方法:

    export function baseHrefFactory(): string {
      const expectedBaseHref = '/my/app';
      const currentBaseHref = window.location.pathname.substr(0, expectedBaseHref.length);
      if (expectedBaseHref.toLowerCase() === currentBaseHref.toLowerCase() && expectedBaseHref !== currentBaseHref)
      {
        // The two base hrefs are the same, but not the same case.
        // Redirect the user to the correct base href.
        const newLocation = window.location.href.replace(currentBaseHref, expectedBaseHref);
        window.location.replace(newLocation);
      }
    
      // this is the case for localhost (where we don't use a virtual directory)
      return currentBaseHref;
    }
    
    @NgModule({
    /**/
      providers: [
        {provide: APP_BASE_HREF, useFactory: baseHrefFactory}
      ]
    })
    export class AppModule
    

    【讨论】:

    • 谢谢回答!但是工厂函数不返回任何内容。
    • 道歉 - 我正在清理我的代码,以便我可以发布它并删除太多。现已更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2012-10-26
    • 2020-10-09
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多