IIS上的AngularJS 2路由

时间:2017-06-21 16:05:28

标签: angular iis asp.net-core

我有一个使用angular2路由的ASP.NET CORE应用程序。运行本地路由按预期解析。当我发布到服务器(运行IIS 7)时,路由似乎添加了我发布它的文件夹目录。在下面的示例中,"页面网址"是我导航到的页面,但是"结果网址是#34;是浏览器地址栏中显示的内容。

page url - > http://myserver/orders

结果网址 - > http://myserver/orders/orders

有关为何发生这种情况的任何想法?这是IIS设置,还是Angular路由问题或.NET CORE配置问题?

以下是我在angular2中配置路线的方法。

export const appRoutes:Routes = [
{ path: 'orders', component: OrderSearchComponent, resolve: {orders: OrderSearchResolverService}},
{ path: 'orders/new', component: CreateOrderComponent},
{ path: 'orders/:id', component: OrderDetailComponent, canActivate: [OrderRouterActivator]},
{ path: '404', component: Error404Component},
{ path: '', redirectTo: 'orders', pathMatch: 'full'},
{ path: 'user', loadChildren: 'app/user/user.module#UserModule' }
]

在我的开发框中,href设置为:

<base href="/">

这在IIS上没有用,所以我尝试了很多不同的设置而没有运气。

<base href=""> and <base href="/order/"> both return:

http://myserver/orders/orders

有什么建议吗?

编辑 - 显示appRoutes的使用位置。

@NgModule({
  ...
imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
 ]...

1 个答案:

答案 0 :(得分:0)

确保您的Startup.cs具有默认路由的路由配置以及为所有路由提供index.cshtml或等效的SPA后备路由,而不是尝试根据客户端导航加载资产

MapSpaFallbackRoute()需要在您的应用程序中安装Microsoft.AspNetCore.SpaServices

按如下方式配置Startup.cs

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }

根据docs,如果您使用 IIS 而非 IIS Express ,则需要创建重写规则并将基本设置为<base href="/src/" />。文档中提供的web.config重写规则如下:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/src/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

这会重写每个请求,因此如果您需要调用API或类似内容,则需要相应地修改<match url="..." />属性。

希望这有帮助!