新建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. Python开发【第四章】:函数剖析

    一.Python函数剖析 1.函数的调用顺序 #!/usr/bin/env python # -*- coding:utf-8 -*- #-Author-Lian #函数错误的调用方式 def fun ...

  2. C++ std::string 在一个字符串前插入一个字符串几种方式

    目录 1.直接使用字符串相加 2.使用insert函数 比较:通过Quick C++ Benchmarks 可得到结果 1.直接使用字符串相加 std::string a = "hello& ...

  3. Django之ORM相关操作

    一般操作 常用的13个操作 <1> all(): 查询所有结果 <2> filter(**kwargs): 它包含了与所给筛选条件相匹配的对象 <3> get(** ...

  4. S03_CH10_DMA_4_Video_Stitch视频拼接系统

    S03_CH10_DMA_4_Video_Stitch视频拼接系统 10.1概述 注意:本课程和上一课程<S03_CH09_DMA_4_Video_Switch视频切换系统>基本相同,不同 ...

  5. Linux下/etc/login.defs文件

    /etc/login.defs文件定义了与/etc/password和/etc/shadow配套的用户限制设定.这个文件是需要的,缺失并不会影响系统的使用,但是也许会产生意想不到的错误. 如果/etc ...

  6. hdu 6216 A Cubic number and A Cubic Number

    题意:给定一个素数,判定它是不是两个立方数之差. 题解:对于a^3+b^3=(a-b)(a^2-a*b+b^2),而一个素数的因子只有1和其本身,在加上(a^2-a*b+b^2)一定是大于1的,所以只 ...

  7. ORACLE:锁被未决分布式事务处理 18.27.160617 持有

    1. 以管理员账号登陆 2. rollback  force '18.27.160617 ';

  8. Xamarin(Android)制作启动画面

    1.将启动图片保存到Drawable文件夹下 2.在Drawable文件夹下创建splashscreen.xml <?xml version="1.0" encoding=& ...

  9. springboot mvc自动配置(三)初始化mvc的组件

    所有文章 https://www.cnblogs.com/lay2017/p/11775787.html 正文 在springboot mvc自动配置的时候,获得了DispatcherServlet和 ...

  10. Uploadify 之使用

    uploadify 3.2.1是 jQuery提供的一个上传插件,其参数详解见 http://www.cnblogs.com/yangy608/p/3915349.html 这里列举一个实际应用的例子 ...