Skip to content

Instantly share code, notes, and snippets.

@poychang
Last active December 4, 2021 09:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poychang/c98f5b35e11f56ad22ff6de6ab09974d to your computer and use it in GitHub Desktop.
Save poychang/c98f5b35e11f56ad22ff6de6ab09974d to your computer and use it in GitHub Desktop.
[ASP.NET Core Middleware 存取 SPA 網頁資源] 搭配 SPA 前端框架使用,將網頁導向至 index.html #dotnet #angular
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace DemoApp.Middleware
{
/// <summary>SPA 中介程序</summary>
public class SpaMiddleware
{
private readonly RequestDelegate _next;
/// <summary>建構式</summary>
public SpaMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>任務調用</summary>
/// <remarks>使用 index.html 存取網頁資源</remarks>
public async Task Invoke(HttpContext context)
{
await _next.Invoke(context);
if (context.Response.StatusCode == 404 && // 該資源不存在
!System.IO.Path.HasExtension(context.Request.Path.Value) && // 網址最後沒有帶副檔名
!context.Request.Path.Value.StartsWith("/api")) // 網址不是 /api 開頭(不是發送 API 需求)
{
context.Request.Path = "/index.html"; // 將網址改成 /index.html
context.Response.StatusCode = 200; // 並將 HTTP 狀態碼修改為 200 成功
await _next.Invoke(context);
}
}
}
/// <summary>SPA 中介程序的擴充方法</summary>
public static class SpaExtensions
{
/// <summary>存取 SPA 網頁資源</summary>
/// <param name="builder">中介程序建構器</param>
public static IApplicationBuilder UseSpaStaticFiles(this IApplicationBuilder builder)
{
return builder.UseMiddleware<SpaMiddleware>();
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DemoApp.Middleware;
namespace DemoApp
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// 存取 SPA 網頁資源
app.UseSpaStaticFiles();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment