中间件
*
*
IApplicationBuilder
*
RequestDelegate 管道
RequestDelegate 是一个委托,它代表一项请求处理任务,是以委托形式对 HttpContext 的封装
*
HttpContext
*
HttpRequest
*
HttpResponse
*
*
*
*
*
*
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
#region 中间件
//app.UseMiddleware<AdminSafeListMiddleware>(Configuration["AdminSafeList"]);
app.UseMiddleware<AuthorizeMiddleware>();
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Hello World 1");
await next();
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World 2");
});
#endregion
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
HTTP 管道中间件
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AuthService
{
public class AuthorizeMiddleware
{
private readonly RequestDelegate _next;
public AuthorizeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
var statusCode = context.Response.StatusCode;
}
finally
{
var statusCode = context.Response.StatusCode;
var msg = String.Empty;
if (statusCode == 400)
{
await HandleExceptionAsync(context, statusCode, "");
}
else if (statusCode == 401)
{
context.Response.OnStarting(state =>
{
var httpContext = (HttpContext)state;
httpContext.Response.Headers.Add("test2", "testvalue2");
httpContext.Response.StatusCode = 401;
httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { code = "401", msg = "Unauthorized" }));
return Task.FromResult(0);
}, context);
}
}
await _next(context);
}
private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
{
return context.Response.WriteAsync(JsonConvert.SerializeObject(new { code = "401", msg = "Unauthorized" }));
}
}
}
*
*
*
*
*
*