NETCORE 使用中间件获取请求头
NETCORE 使用中间件获取请求头
创建项目:框架 net6 web api:
项目名称:NETCORE.RequestHead
1. 创建中间件 RequestHeaderVerificationMiddleware.cs
using Microsoft.Extensions.Primitives; using System.Diagnostics; namespace ApiMiddleware.Middleware { public class RequestHeaderVerificationMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; /// <summary> /// 计时器 /// </summary> private Stopwatch _stopwatch; private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms"; public RequestHeaderVerificationMiddleware(RequestDelegate next, ILogger<RequestHeaderVerificationMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { _stopwatch = new Stopwatch(); _stopwatch.Start(); _logger.LogError($"Handling request: {context.Request.Path}"); StringValues token = ""; context.Request.Headers.TryGetValue("token", out token);
context.Request.Headers.TryGetValue("Authorization", out token);
var tokenBody = token.ToString().Substring("Bearer ".Length);
var jwtSecurityToken = new JwtSecurityTokenHandler().ReadJwtToken(tokenBody);
BaseInfo.userId = Convert.ToInt32(jwtSecurityToken.Subject.Split("|")[0]);
BaseInfo.loginName = jwtSecurityToken.Subject.Split("|")[1];
var userinfo = jwtSecurityToken.Claims.FirstOrDefault(o => o.Type == "Name")?.Value;
var claims = context.User.Claims;
//获取到请求头中的 token 数据 //if (!context.Request.Headers.TryGetValue("request_id", out String Values request_id) || string.IsNullOrEmpty(request_id)) //{ // await HandleMessage(context, JsonConvert.SerializeObject(new { msg = "request_id不可为空", request_id = request_id })); // goto step; //} //if (!context.Request.Headers.TryGetValue("uname", out StringValues uname) || string.IsNullOrEmpty(uname)) //{ // await HandleMessage(context, JsonConvert.SerializeObject(new { msg = "名称不可为空", request_id = request_id, uname = uname })); // goto step; //} context.Response.OnStarting(() => { // Stop the timer information and calculate the time _stopwatch.Stop(); var responseTimeForCompleteRequest = _stopwatch.ElapsedMilliseconds; // Add the Response time information in the Response headers. context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString(); return Task.CompletedTask; }); if (!context.Response.HasStarted) { await _next(context); } } } }
创建类 MyMiddlewareExtensions.cs
using Microsoft.AspNetCore.Builder; namespace ApiMiddleware.Middleware { public static class MyMiddlewareExtensions { public static void UseMyMiddleware(this IApplicationBuilder builder) { builder.UseMiddleware<RequestHeaderVerificationMiddleware>(); } } }
在 program.cs 中,注册中间件
app.UseMyMiddleware();//注册中间件
测试 postman
调用项目中的接口时,在请求头中加入自定义 token ,可获取到。
引用:http://t.zoukankan.com/personblog-p-12582673.html