首页 > 其他分享 >NETCORE 使用中间件获取请求头

NETCORE 使用中间件获取请求头

时间:2022-11-10 16:14:26浏览次数:45  
标签:请求 NETCORE 中间件 request Response uname context id

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);
            //获取到请求头中的 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

 

标签:请求,NETCORE,中间件,request,Response,uname,context,id
From: https://www.cnblogs.com/1285026182YUAN/p/16877362.html

相关文章

  • spring mvc 请求异步处理,即时响应
    springmvc的controller,对于一个非常耗时的处理,让controller先异步返回响应给前端,后台继续慢慢执行完。@RequestMapping(value="refreshScore.do",method=Reque......
  • netcore 处理long(雪花Id)精度丢失
    一、扩展修改(Snowflake.Core)    ①、安装依赖包Install-PackageSnowflake.Core     ②、扩展重写  1、扩展雪花Id,通过更改基数生成数字坐落于(6......
  • Nginx基于请求头的分发
    前面介绍的分发方式适用于单个集群,而基于请求头分发适用于多个集群场景。基于请求头的分发1、基于host分发:适用于一个公司有多个网站,一个网站设置为一个集群#nginx分发......
  • 请求与响应——日期类型参数传递
    1.  2.格式的转换都是靠下面这个类型转换器实现的 ......
  • 关于前端:如何实现并发请求数量控制?
    原文地址: https://juejin.cn/post/7163522138698153997//并发请求函数constconcurrencyRequest=(urls,maxNum)=>{returnnewPromise((resolve)=>{......
  • Vuex中actions如何优雅处理接口请求
    前言在项目开发中,如果使用到了vuex,通常我会将所有的接口请求单独用一个文件管理,而业务逻辑写在actions中,一方面方便统一管理项目中的所有请求,其次代码结构更加清晰,最重......
  • http 请求头UA收集
    "User-Agent":random.choice(["Mozilla/5.0(WindowsNT10.0;WOW64)",'Mozilla/5.0(WindowsNT6.3;WOW64)',......
  • 0009.Django请求与响应
    HttpRequest对象服务器接受到http协议的请求后,会根据报文创建HttpRequest对象视图函数的第一个参数是HttpRequest对象在django.http模型中定义了HttpRequest对象的API......
  • ASP.NET Core 中间件的几种实现方式
    原文网址:https://article.itxueyuan.com/56jL59匿名函数通常新建一个空的ASP.NETCoreWebApplication,项目名字无所谓啦在启动类里可以看到这么一句://Startup.cs......
  • NetCore3.1引入Nlog
    十年河东,十年河西,莫欺少年穷学无止境,精益求精Net6引入Nlog请参考:https://www.cnblogs.com/chenwolong/p/nlog.html项目引入:<PackageReferenceInclude="NLog"V......