如何在特定路线上在现有MVC应用程序中启用Spa中间件

时间:2018-08-14 10:03:20

标签: c# asp.net-core single-page-application asp-net-core-spa-services

默认情况下,站点根上已启用SPA。但是,我想将其移至特定路径,例如:http://localhost:port/frontend

//public void ConfigureServices(IServiceCollection services)
services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "ClientApp/dist/myApp";
});

//public void Configure(IApplicationBuilder app)
app.Map("/frontend", frontendApp =>
{
    frontendApp.UseSpaStaticFiles(new StaticFileOptions
    {
        RequestPath = "/frontend'
    });
    frontendApp.UseSpa(spa =>
    {
        spa.Options.SourcePath = "/ClientApp"; 
        if (Configuration.GetValue<bool>("UseAngularCliServer"))                     
        {
           spa.UseProxyToSpaDevelopmentServer("http://localhost:4200/");
        }
    });
});

当我在/ frontend文件夹中运行npm build时,这将起作用,但是在配置UseProxyToSpaDevelopmentServer时遇到问题。它显示了index.html,但是引用了

http://localhost:port/vendor.js而不是http://localhost:port/frontend/vendor.js

当我使用ng serve --base-href=/vnext/

对localhost:port / frontend / vendor.js的请求返回index.html的内容。

2 个答案:

答案 0 :(得分:1)

可能您应该使用frontendApp参数而不是app

app.Map("/frontend", frontendApp =>
{
    frontendApp.UseSpaStaticFiles(new StaticFileOptions
    {
        //RequestPath = ??
    });
    frontendApp.UseSpa(spa =>
    {
        //spa.Options.DefaultPageStaticFileOptions.RequestPath = ??;
        spa.Options.SourcePath = "/ClientApp"; 
    });
});

答案 1 :(得分:0)

要请求http://localhost:port/frontend/vendor.js,我们需要指定-base-href ,建议您尝试使用以下package.json中的脚本:

"start": "ng serve --base-href=/frontend/ --serve-path=/ --live-reload-client=https://localhost:port/frontend/sockjs-node/",

对于另一种选择,您可以尝试以下Startup

中的代码
        app.Map("/frontend", frontendApp =>
        {
            frontendApp.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start --  --base-href=/frontend/ --serve-path=/ --live-reload-client=https://localhost:44302/frontend/sockjs-node/");
                }
            });
        });