新建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. kibana发音 logstash发音 ElasticSearch发音 音标 翻译

    kibana [kɪbana] 剋吧那 kei ba na == 扩展 logstash [lɔɡ] [stæ:ʃ] 楼个四die吃 == ElasticSearch [ɪˈlæstɪk] [sɜːt ...

  2. Word 查找替换高级玩法系列之 -- 用替换功能删除空白区域

    当你遇到Word文档中时不时的出现一些空白区域的时候会怎么办呢?一个个删除吗?NO!NO!NO!!!那样也太慢了!仅使用替换功能就可以帮你一步搞定它! 下面这篇文档中含有半角空格.全角空格.不间断空格 ...

  3. 排查java 内存CPU报警

    #!/bin/bash source /etc/profile #接收外部传入PID,任选一种 #servicePid=$1 headPid=`ps auxw|sort -rn -k3|head -4 ...

  4. 十、LCD的framebuffer设备驱动

    在读者学习本章以及后续LCD相关章节之前,最好拥有LCD裸机基础,可以参考:LCD编程. 在内核中,表示LCD使用的是framebuffer(帧缓冲,简写为fb),其内容对应于屏幕上的界面显示.修改f ...

  5. SAS学习笔记32 select语句

  6. Asp.Net Core 轻松学系列-2从安装环境开始

    Asp.Net Core 介绍     Asp.Net Core是微软新一代的跨平台开发框架,基于 C# 语言进行开发,该框架的推出,意味着微软从系统层面正式进击 Linux 服务器平台:从更新速度开 ...

  7. Java内存模型(JMM)

    JVM与线程(线程在JVM中) 1.JVM什么时候启动?         类被调用时启动,此时会启动JVM线程然后再是其他的线程(main) 2.JVM内存区域 除了程序计数器(PC)之外都有可能发生 ...

  8. 监控神器-普罗米修斯Prometheus的安装

    搬砖党的福音:普罗米修斯-监控神器 功能: 在业务层用作埋点系统 Prometheus支持多种语言(Go,java,python,ruby官方提供客户端,其他语言有第三方开源客户端).我们可以通过客户 ...

  9. Windows10+Android Studio 3.5编译项目报错——NDK Resolution Outcome: Project settings: Gradle model version=4.10.1, NDK version is UNKNOWN

    项目背景: 系统有C.D两个盘,Android Studio安装在D盘,sdk安装在C盘. 出现的问题: 从git拉取项目后,一直编译不通过,提示“NDK Resolution Outcome: Pr ...

  10. 获取select标签的自定义属性

    $("#ddlUsers").find("option:selected").attr("fullstr"); fullstr就是自定义属性 ...