【问题标题】:How to host Angular application with Kestrel如何使用 Kestrel 托管 Angular 应用程序
【发布时间】:2019-05-18 22:14:05
【问题描述】:

我正在尝试使用Kestrel 使用FileProvider 扩展部署Angular 7 应用程序和.NET Core

我已经创建了 Angular 应用程序,我有 ng build 它,我复制了 dist .NET Porject 中的文件。

启动

 public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        string jsFolderName = "myroot";
        string prodRoot =Path.Combine(AppDomain.CurrentDomain.BaseDirectory,jsFolderName);
        string debugRoot =Path.Combine(Directory.GetCurrentDirectory(),jsFolderName);

        var isDev=env.IsDevelopment();


        DefaultFilesOptions options = new DefaultFilesOptions();
        options.DefaultFileNames.Clear();
        options.DefaultFileNames.Add("/myroot/index.html");
        app.UseDefaultFiles(options);
        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions() {
            FileProvider = new PhysicalFileProvider(isDev?debugRoot:prodRoot),
            RequestPath = "/app"
        });
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        } else {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }

P.S 我的myroot 文件夹就在项目的根目录中。 我不知道如何提供angular 应用程序的第一页(入口点),即index.html

【问题讨论】:

标签: asp.net-core ng-build fileprovider-extension


【解决方案1】:

正如@Simonare在评论中所建议的,最好的方法是使用官方的Angular模板。

但如果您只想提供静态文件,您可以执行以下操作:

  1. DefaultFilesOptions 配置为FileProviderRequestPath
var fileProvider = new PhysicalFileProvider(isDev?debugRoot:prodRoot); DefaultFilesOptions 选项 = 新的 DefaultFilesOptions(){ RequestPath = "/app", // 处理对`/app`的请求 FileProvider = fileProvider, // 检查 `myroot/**/**` 下的文件 DefaultFileNames = 新列表 { "index.html" }, }; options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("/myroot/index.html"); app.UseDefaultFiles(选项); // 提供静态文件 app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { RequestPath = "/app", 文件提供者 = 文件提供者, });
  1. 因为app的路径是https://yourhost:port/app,所以你还需要更改index.html内的基本路径,这样浏览器才会加载所有资源(例如js、css、img文件)相对于当前路径。 /src/index.html的原始基数是/

    <!doctype html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>App</title>
            <base href="/">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="icon" type="image/x-icon" href="favicon.ico">
        </head>
        <body>
            <app-root>Loading...</app-root>
        </body>
    </html>

注意我们需要:

  • &lt;base href="/"&gt;改为&lt;base href="/app"&gt;
  • 或将基数更改为空字符串:&lt;base href=""&gt;
  • 或删除该行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 2020-07-26
    相关资源
    最近更新 更多