在子文件夹下部署Angular SPA

时间:2018-11-07 20:20:29

标签: angular iis asp.net-core single-page-application asp.net-core-2.1

我有一个使用Visual Studio 2017 Angular项目模板创建的ASP.net Core 2.1 Web API + Angular 6 Web应用程序。 api和Angular应用程序都在同一个Web项目中。在开发中,它运行在IIS Express中,而在生产中,它使用IIS。

该应用程序本身运行良好,但是我很难将其部署到现有网站的子文件夹中,该子文件夹在IIS中配置为新的Web应用程序。

当我将URL调用为:

Angular能够正确构建相对路径,并且应用程序可以很好地加载。

当我以如下方式访问网址时(请注意缺少尾随的斜杠):

IIS服务于index.html网页(为什么?我希望输入404!),但是Angular无法正确计算到JS / CSS资源的相对路径。

我尝试使用Microsoft.AspNetCore.Rewrite模块将^$路径重定向到/index.html并起作用,但是它也重写了原来的工作请求,地址栏中出现了难看的闪光:

http://localhost:52000/AngularWebApp/ => http://localhost:52000/AngularWebApp/index.html => http://localhost:52000/AngularWebApp/#/dashboard

我尝试重定向到#/,但Chrome停止了使用ERR_TOO_MANY_REDIRECTS的请求。

这个问题有解决方案吗?请注意,我需要一个通用的解决方案,该解决方案使我可以在子文件夹下或在其自己的域下发布Web应用程序,而无需重建应用程序。

相关片段:

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
...
app.UseRewriter(new RewriteOptions()
   .AddRedirect(@"^$", "/index.html", (int)HttpStatusCode.MovedPermanently));

app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(...);
app.UseSpa(...);
...
}

index.html

<base href="./">

预先感谢您的帮助

2 个答案:

答案 0 :(得分:0)

设置host,并确保dist角文件位于<base href="/AngularWebApp" />文件夹中。

在“启动”中,您可以执行以下操作:

wwwroot/AngularWebApp

参考:https://medium.com/@levifuller/building-an-angular-application-with-asp-net-core-in-visual-studio-2017-visualized-f4b163830eaa

答案 1 :(得分:0)

https://github.com/aspnet/BasicMiddleware/blob/268290a8b56fe44d0e03cbd69d78ba7a17b4f2c1/src/Microsoft.AspNetCore.Rewrite/Internal/RedirectRule.cs#L47检查了重定向中间件的代码后,很明显,所提供的重定向中间件不允许在不重定向根('/')路径的情况下重定向空路径('')。

但是,从该代码中汲取灵感后,很容易建立一个满足我需要的自定义重写规则:

// Load the index.html page when the url is invoked without the ending '/'
// Avoids problems with Angular when loading http://domain/AngularWebApp instead of http://domain/AngularWebApp/
app.UseRewriter(new RewriteOptions().Add(rewriteContext =>
    {
        var request = rewriteContext.HttpContext.Request;
        if (request.Path == PathString.Empty)
        {
            rewriteContext.HttpContext.Response.Redirect(request.PathBase + '/', true);
            rewriteContext.Result = RuleResult.EndResponse;
        }
    }));

现在,即使将Angular Web应用程序部署在其自己的根域或子文件夹下,也可以正确加载,即使用户在没有尾部斜杠字符的情况下调用它也是如此。

相关问题