.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和 ...
随机推荐
- golang中switch用法细节
1. switch穿透-fallthrough, 如果在case语句块后增加fallthrough,则会继续执行下一个case,也叫switch穿透,默认只穿透一层 2. Type Switch: s ...
- rm 参数列表过长
刚摸索了一个小技巧,有时候在删除文件的时候,文件很多,直接用rm -rf * ,会报错误“rm 参数列表过长”. 这时候网上的办法一般都是通过类似的办法:find . -name "&quo ...
- 【C#】课堂知识点#2
课堂上老师讲了几点,自己觉得挺重要的,记录下来 1.代码字体调大,方便调试 2.虚心请教,没有谁比谁厉害,不会就虚心多请教,baidu并不能解决所有问题.沟通交流也是一种能力 3.只有每行写对了,才继 ...
- canvas绘制文本自动换行
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8&quo ...
- CTS & APIO 2019 游记
写在前面 算是省选后的第一轮大考. 去年因为某些原因并没有参加 CTSC 以及 APIO,还是有些遗憾,所以希望今年能有所收获. 也希望今年的 CTS 能延续去年的出题风格,这样我还能苟一两个题. 然 ...
- Junit 学习1 junit的简单使用
package junit; import java.sql.Connection; import java.sql.SQLException; import org.junit.Test; impo ...
- kong网关命令(一)
上次在虚拟机里安装kong网关后,因为版本(1.4)太高,目前Kong Dashboard无法支持, 后续发现Git上有个开源工具Kong admin ui,下载源码并部署到NGINX. 但是发现使用 ...
- Redis二进制安全概念
二进制安全是指,在传输数据时,保证二进制数据的信息安全,也就是不被篡改.破译等,如果被攻击,能够及时检测出来. 二进制安全包含了密码学的一些东西,比如加解密.签名等. 举个例子,你把数据1111000 ...
- iframe内嵌页面——跨域通讯
<template> <div class="act-form"> <iframe :src="src" ref=" ...
- Java流对象:InputStream、OutputStream、Reader、Writer
流对象使用完一般要用close方法关闭.释放资源. InputStream 和OutPutStream 二者都是字节输入和输出的抽象父类,子字节为单位处理数据,每次读取.写入一个字节,适合处理二进制文 ...