新建standard类库项目,添加引用包

Microsoft.AspNetCore

1、扩展IApplicationBuilder

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using System; namespace MiddleWareLib.Middlewares
{
public static class PracticeAuthenticationExtensions
{
public static IApplicationBuilder UsePracticeAuthentication(this IApplicationBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
} return builder.UseMiddleware<PracticeAuthenticationMiddleware>();
} public static IApplicationBuilder UsePracticeAuthentication(this IApplicationBuilder builder, PracticeAuthenticationOptions options)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
} if (options == null)
{
throw new ArgumentNullException(nameof(options));
} return builder.UseMiddleware<PracticeAuthenticationOptions>(Options.Create(options));
}
}
}

2、定义中间件

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Newtonsoft.Json; namespace MiddleWareLib
{
public class PracticeAuthenticationMiddleware
{
private readonly PracticeAuthenticationOptions _options; private readonly RequestDelegate _next; public PracticeAuthenticationMiddleware(RequestDelegate next, IOptions<PracticeAuthenticationOptions> options)
{
this._next = next;
this._options = options.Value;
} public async Task InvokeAsync(HttpContext context)
{
await Check(context);
await _next.Invoke(context);
} #region MyRegion
/// <summary>
/// the main check method
/// </summary>
/// <param name="context"></param>
/// <param name="requestInfo"></param>
/// <returns></returns>
private async Task Check(HttpContext context)
{
string computeSinature =$"{context.Request.Query["appid"]}-{context.Request.Query["timestamp"]}";
double tmpTimestamp;
if (computeSinature.Equals(context.Request.Query["sign"]) &&
double.TryParse(context.Request.Query["timestamp"], out tmpTimestamp))
{
if (CheckExpiredTime(tmpTimestamp, _options.ExpiredSecond))
{
await ReturnResponse(context,, "验证失败");
}
else
{
await ReturnResponse(context, , "验证成功");
}
}
else
{
await ReturnResponse(context);
}
}
/// <summary>
///响应
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private async Task ReturnResponse(HttpContext context,int statu=,string msg= "Time Out!")
{
context.Response.StatusCode = statu;
await context.Response.WriteAsync(JsonConvert.SerializeObject(new{ Code = statu, Message =msg }));
}
/// <summary>
/// 签名超时
/// </summary>
/// <param name="timestamp"></param>
/// <param name="expiredSecond"></param>
/// <returns></returns>
private bool CheckExpiredTime(double timestamp, double expiredSecond)
{
double now_timestamp = (DateTime.UtcNow - new DateTime(, , )).TotalSeconds;
return (now_timestamp - timestamp) > expiredSecond;
}
#endregion
}
}

3、自定义中间件配置

using System;
using System.Collections.Generic;
using System.Text; namespace MiddleWareLib
{
public class PracticeAuthenticationOptions
{
public string EncryptKey { get; set; } public int ExpiredSecond { get; set; }
}
}

4、扩展IServiceCollection

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection; namespace MiddleWareLib
{
public static class PracticeAuthenticationServicesExtensions
{
public static IServiceCollection AddPracticeAuthentication(this IServiceCollection services)
{
if (services==null)
{
throw new ArgumentNullException(nameof(services));
}
return services;
}
public static IServiceCollection AddPracticeAuthentication(this IServiceCollection services,Action<PracticeAuthenticationOptions> PracticeAuthenticationOptions)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if(PracticeAuthenticationOptions == null)
{
throw new ArgumentNullException(nameof(PracticeAuthenticationOptions));
}
services.Configure(PracticeAuthenticationOptions);
return services;
}
}
}

.Net Core:Middleware自定义中间件的更多相关文章

  1. Asp.Net Core 通过自定义中间件防止图片盗链的实例(转)

    一.原理 要实现防盗链,我们就必须先理解盗链的实现原理,提到防盗链的实现原理就不得不从HTTP协议说起,在HTTP协议中,有一个表头字段叫referer,采用URL的格式来表示从哪儿链接到当前的网页或 ...

  2. .NET Core 自定义中间件 Middleware

    引言 很多看了上一章的朋友私信博主,问如何自定义,自己的中间件(Middleware),毕竟在实际的项目中,大家会有很多需求要用到中间件,比如防盗链.缓存.日志等等功能,于是博主这边就简单讲解一下框架 ...

  3. ASP.NET Core 1.1 静态文件、路由、自定义中间件、身份验证简介

    概述 之前写过一篇关于<ASP.NET Core 1.0 静态文件.路由.自定义中间件.身份验证简介>的文章,主要介绍了ASP.NET Core中StaticFile.Middleware ...

  4. ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介

    概述 ASP.NET Core 1.0是ASP.NET的一个重要的重新设计. 例如,在ASP.NET Core中,使用Middleware编写请求管道. ASP.NET Core中间件对HttpCon ...

  5. asp.net core中写入自定义中间件

    首先要明确什么是中间件?微软官方解释:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?tabs=aspnet ...

  6. NET Core 1.1 静态文件、路由、自定义中间件、身份验证简介

    NET Core 1.1 静态文件.路由.自定义中间件.身份验证简介   概述 之前写过一篇关于<ASP.NET Core 1.0 静态文件.路由.自定义中间件.身份验证简介>的文章,主要 ...

  7. .NET Core 3.0 中间件 Middleware

    中间件官网文档解释:中间件是一种装配到应用管道以处理请求和响应的软件 每个中间件: 选择是否将请求传递到管道中的下一个组件. 可在管道中的下一个组件前后执行工作. 使用 IApplicationBui ...

  8. 翻译 - ASP.NET Core 基本知识 - 中间件(Middleware)

    翻译自 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0 中间件是集成 ...

  9. 如何在ASP.NET Core自定义中间件中读取Request.Body和Response.Body的内容?

    原文:如何在ASP.NET Core自定义中间件中读取Request.Body和Response.Body的内容? 文章名称: 如何在ASP.NET Core自定义中间件读取Request.Body和 ...

随机推荐

  1. 【Docker】:docker安装ELK(logstash,elasticsearch,kibana)

    一:安装logstash 1.拉取镜像 docker pull logstash:5.6.11 2.创建目录 mkdir /docker/logstash cd /docker/logstash 3. ...

  2. SQL概要与表的创建

    SQL概要与表的创建 1.表的结构 ​ 关系数据库通过类似Excel 工作表那样的.由行和列组成的二维表来管理数据.用来管理数据的二维表在关系数据库中简称为表. ​ 根据SQL 语句的内容返回的数据同 ...

  3. js — 数组Array

    目录 1. isArray 2. 转换方法 3. 分割字符串 join 4. 栈方法 5. 队列方法 6. 重排序方法 7. 操作方法 8. 位置方法 - 索引 9. 迭代方法 数组 array 解释 ...

  4. java字节和字符的区别

    字节: 1.bit=1  二进制数据0或1 2.byte=8bit  1个字节等于8位 存储空间的基本计量单位 3.一个英文字母=1byte=8bit 1个英文字母是1个字节,也就是8位 4.一个汉字 ...

  5. 应用人员反馈报错,ORA-03137: TTC protocol internal error : [12333]

    一.报错现象 应用人员反馈连接不上数据库,连接报错. 我们使用PLSQL发现可以连接数据库,但是数据库DB Alert存在如下报错信息 DB AlertFri Oct :: Errors ): ORA ...

  6. HTTP抓包

    1 概述 wireshark:全平台抓包工具,需要图形化界面,十分强大: httpry:http抓包插件,功能一般,操作简单: tcpdump:强大的抓包插件,支持多种网络协议. 2 httpry ( ...

  7. 【SQL Server性能优化】运用SQL Server的全文检索来提高模糊匹配的效率

    原文:[SQL Server性能优化]运用SQL Server的全文检索来提高模糊匹配的效率 今天去面试,这个公司的业务需要模糊查询数据,之前他们通过mongodb来存储数据,但他们说会有丢数据的问题 ...

  8. SqlServer用sql语句清理log日志

    原文:SqlServer用sql语句清理log日志 USE[master] ALTER DATABASE [Center] SET RECOVERY SIMPLE WITH NO_WAIT ALTER ...

  9. Java数据结构总述

    array list map set 链表..array 和list类似,增删慢,读取快,list长度可变,array长度固定, 链表增删快的list set 是一个没有重复数据的集合 map 是一个 ...

  10. kong命令(三)route

    介绍 route 是一套匹配客户端请求的规则.每个route都会匹配一个service,每个service可定关联多个route. 可以说service:route=1:n.一对多的关系.每个匹配到r ...