.Net Core:Middleware自定义中间件
新建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自定义中间件的更多相关文章
- Asp.Net Core 通过自定义中间件防止图片盗链的实例(转)
一.原理 要实现防盗链,我们就必须先理解盗链的实现原理,提到防盗链的实现原理就不得不从HTTP协议说起,在HTTP协议中,有一个表头字段叫referer,采用URL的格式来表示从哪儿链接到当前的网页或 ...
- .NET Core 自定义中间件 Middleware
引言 很多看了上一章的朋友私信博主,问如何自定义,自己的中间件(Middleware),毕竟在实际的项目中,大家会有很多需求要用到中间件,比如防盗链.缓存.日志等等功能,于是博主这边就简单讲解一下框架 ...
- ASP.NET Core 1.1 静态文件、路由、自定义中间件、身份验证简介
概述 之前写过一篇关于<ASP.NET Core 1.0 静态文件.路由.自定义中间件.身份验证简介>的文章,主要介绍了ASP.NET Core中StaticFile.Middleware ...
- ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介
概述 ASP.NET Core 1.0是ASP.NET的一个重要的重新设计. 例如,在ASP.NET Core中,使用Middleware编写请求管道. ASP.NET Core中间件对HttpCon ...
- asp.net core中写入自定义中间件
首先要明确什么是中间件?微软官方解释:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?tabs=aspnet ...
- NET Core 1.1 静态文件、路由、自定义中间件、身份验证简介
NET Core 1.1 静态文件.路由.自定义中间件.身份验证简介 概述 之前写过一篇关于<ASP.NET Core 1.0 静态文件.路由.自定义中间件.身份验证简介>的文章,主要 ...
- .NET Core 3.0 中间件 Middleware
中间件官网文档解释:中间件是一种装配到应用管道以处理请求和响应的软件 每个中间件: 选择是否将请求传递到管道中的下一个组件. 可在管道中的下一个组件前后执行工作. 使用 IApplicationBui ...
- 翻译 - ASP.NET Core 基本知识 - 中间件(Middleware)
翻译自 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0 中间件是集成 ...
- 如何在ASP.NET Core自定义中间件中读取Request.Body和Response.Body的内容?
原文:如何在ASP.NET Core自定义中间件中读取Request.Body和Response.Body的内容? 文章名称: 如何在ASP.NET Core自定义中间件读取Request.Body和 ...
随机推荐
- MySQL合理配置连接池数量
我们经常会遇见“MySQL:ERROR1040:Toomanyconnections”的情况,一种是访问量确实很高,MySQL服务器抗不住,这个时候就要考虑增加从服务器分散读写压力,另外一种情况是 ...
- IP地址 子网掩码 网络地址 主机地址 广播地址
1.一定要明白各自的概念分别表示什么 IP地址:IP地址是用来识别网络上的设备,因此,IP地址是由网络地址与主机地址两部分所组成. 子网掩码:子网掩码不能单独存在,它必须结合IP地址一起使用.子网掩码 ...
- MySQL忘记密码解决
1.设置管理员root密码为123 开启MySQL服务后 PS C:\WINDOWS\system32> mysqladmin -uroot -p password "123" ...
- 写CSDN博客
文章目录 前言 写博客的规范 写博客的小技巧 版权声明模板 博客表格模板 更改博客字体和颜色 LaTeX 数学公式 前言 这是一篇关于写CSDN博客的文章.记录我的博客规范,技巧,模板,心得. 写博客 ...
- DMA存储器到外设代码讲解
实验目的: bsp_dma_mtp.h #ifndef __BSP_DMA_MTP_H #define __BSP_DMA_MTP_H #include "stm32f10x.h" ...
- 【规律】Parentheses
Parentheses 题目描述 Dave loves strings consisting only of '(' and ')'. Especially, he is interested in ...
- D盘Program Files 文件夹里文件不显示,没隐藏。怎么才能显示出来?
D盘里有两个一模一样的Program Files 文件夹,文件夹里文件不显示,没隐藏.怎么才能显示出来?新买不久的电脑,win8.1系统 点击开始---运行---输入“cmd”(没有引号)---在弹出 ...
- LeetCode:626.换座位
题目链接:https://leetcode-cn.com/problems/exchange-seats/ 题目 小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们 ...
- vue 2.0+ 怎么写本地接口获取数据
在vue-cli脚手架项目中,找到build ---- webpack.dev.conf.js 文件,具体位置如下图: 找到文件后添加下面的内容,写在头部: //这是 webpack.dev.conf ...
- js通俗易懂的&&与||或运算
使用&&将返回第一个条件为假的值. 如果每个操作数的计算值都为true, 则返回最后一个计算过的表达式. let one = 1, two = 2, three = 3;console ...