Skip to content

Instantly share code, notes, and snippets.

@poychang
Last active May 22, 2019 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poychang/980fd0bbf7148a6046f323ce5c7f4379 to your computer and use it in GitHub Desktop.
Save poychang/980fd0bbf7148a6046f323ce5c7f4379 to your computer and use it in GitHub Desktop.
[ASP.NET Core Middleware Sample] 範例中包含只允許特定 IP 區段才能存取的功能 #dotnet
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace App.Middleware
{
/// <summary></summary>
public class MyAuthorizedMiddleware
{
private readonly RequestDelegate _next;
/// <summary></summary>
public MyAuthorizedMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary></summary>
public async Task Invoke(HttpContext context)
{
if (context.Request.Path.StartsWithSegments("/api")
&& !context.Connection.RemoteIpAddress.ToString().StartsWith("192.168"))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
//do work before the invoking the rest of the pipeline
await _next.Invoke(context); //let the rest of the pipeline run
//do work after the rest of the pipeline has run
}
}
/// <summary></summary>
public static class MyAuthorizeExtensions
{
/// <summary></summary>
/// <param name="builder">中介程序建構器</param>
public static IApplicationBuilder UseMyAuthorized(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyAuthorizedMiddleware>();
}
}
}
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
namespace Phishing
{
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) {}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.Use(async (context, next) =>
{
await next();
// 判斷是否是要存取網頁,而不是發送 API 需求
if (context.Response.StatusCode == 404 && // 該資源不存在
!System.IO.Path.HasExtension(context.Request.Path.Value) && // 網址最後沒有帶副檔名
!context.Request.Path.Value.StartsWith("/api")) // 網址不是 /api 開頭
{
context.Request.Path = "/index.html"; // 將網址改成 /index.html
context.Response.StatusCode = 200; // 並將 HTTP 狀態碼修改為 200 成功
await next();
}
});
// 使用 Middleware
app.UseMyAuthorized();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment