ASP.NET Core -中间件(Middleware)使用
ASP.NET Core开发,开发并使用中间件(Middleware)。
中间件是被组装成一个应用程序管道来处理请求和响应的软件组件。
每个组件选择是否传递给管道中的下一个组件的请求,并能之前和下一组分在管道中调用之后执行特定操作。
具体如图:

开发中间件(Middleware)
今天我们来实现一个记录ip 的中间件。
1.新建一个asp.net core项目,选择空的模板。
2.新建一个类: RequestIPMiddleware.cs

public class RequestIPMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger; public RequestIPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<RequestIPMiddleware>();
} public async Task Invoke(HttpContext context)
{
_logger.LogInformation("User IP: " + context.Connection.RemoteIpAddress.ToString());
await _next.Invoke(context);
}
}

3.再新建一个:RequestIPExtensions.cs

public static class RequestIPExtensions
{
public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestIPMiddleware>();
}
}

这样我们就编写好了一个中间件。
使用中间件(Middleware)
1.使用
在 Startup.cs 添加 app.UseRequestIP()

public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
{
loggerfactory.AddConsole(minLevel: LogLevel.Information);
app.UseRequestIP();//使用中间件
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}

然后运行程序,我选择使用Kestrel 。
访问:http://localhost:5000/

成功运行。
二、Asp.Net Core使用中间件拦截处理请求
public class OuterImgMiddleware
{
public static string RootPath { get; set; } //配置文件读取绝对位置
private readonly RequestDelegate _next;
public OuterImgMiddleware(RequestDelegate next, IHostingEnvironment env)
{
// _wwwrootFolder = env.WebRootPath;
_next = next;
}
public async Task Invoke(HttpContext context)
{
var path = context.Request.Path.ToString();
var headersDictionary = context.Request.Headers; if (context.Request.Method == "GET")
if (!string.IsNullOrEmpty(path) && path.Contains("/upload/logo"))
{ //var unauthorizedImagePath = Path.Combine(RootPath, path);
var unauthorizedImagePath = RootPath + path;
await context.Response.SendFileAsync(unauthorizedImagePath);
return;
} await _next(context);
}
}
public static class MvcExtensions
{
public static IApplicationBuilder UseOutImg(this IApplicationBuilder builder)
{
return builder.UseMiddleware<OuterImgMiddleware>();
}
}
同上在Configure()中注册使用就可以了。
更多:
Asp.Net Core 通过自定义中间件防止图片盗链的实例(转)
在ASP.NET Core2.0中使用百度在线编辑器UEditor(转)
Asp.Net Core WebAPI入门整理(四)参数获取
ASP.NET Core -中间件(Middleware)使用的更多相关文章
- ASP.NET Core中间件(Middleware)实现WCF SOAP服务端解析
ASP.NET Core中间件(Middleware)进阶学习实现SOAP 解析. 本篇将介绍实现ASP.NET Core SOAP服务端解析,而不是ASP.NET Core整个WCF host. 因 ...
- ASP.NET Core 入门教程 9、ASP.NET Core 中间件(Middleware)入门
一.前言 1.本教程主要内容 ASP.NET Core 中间件介绍 通过自定义 ASP.NET Core 中间件实现请求验签 2.本教程环境信息 软件/环境 说明 操作系统 Windows 10 SD ...
- ASP.NET Core 入门笔记10,ASP.NET Core 中间件(Middleware)入门
一.前言 1.本教程主要内容 ASP.NET Core 中间件介绍 通过自定义 ASP.NET Core 中间件实现请求验签 2.本教程环境信息 软件/环境 说明 操作系统 Windows 10 SD ...
- ASP.NET Core 中间件Diagnostics使用
ASP.NET Core 中间件(Middleware)Diagnostics使用.对于中间件的介绍可以查看之前的文章ASP.NET Core 开发-中间件(Middleware). Diagnost ...
- ASP.NET Core 中间件Diagnostics使用 异常和错误信息
ASP.NET Core 中间件(Middleware)Diagnostics使用.对于中间件的介绍可以查看之前的文章ASP.NET Core 开发-中间件(Middleware). Diagnost ...
- ASP.NET Core 中间件自定义全局异常处理
目录 背景 ASP.NET Core过滤器(Filter) ASP.NET Core 中间件(Middleware) 自定义全局异常处理 .Net Core中使用ExceptionFilter .Ne ...
- [转帖]ASP.NET Core 中间件(Middleware)详解
ASP.NET Core 中间件(Middleware)详解 本文为官方文档译文,官方文档现已非机器翻译 https://docs.microsoft.com/zh-cn/aspnet/core/ ...
- 在ASP.NET Core使用Middleware模拟Custom Error Page功能
一.使用场景 在传统的ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAtt ...
- [转]ASP.NET Core 中间件详解及项目实战
本文转自:http://www.cnblogs.com/savorboard/p/5586229.html 前言 在上篇文章主要介绍了DotNetCore项目状况,本篇文章是我们在开发自己的项目中实际 ...
随机推荐
- JavaScript对象简介(一)
本节介绍js的9个对象:Array数组对象 Boolean(true false) Date日前对象 Math 数学对象 Number 数字对象 String 字符串对象 RegExp 正则表达式对象 ...
- Coursera台大机器学习技法课程笔记05-Kernel Logistic Regression
这一节主要讲的是如何将Kernel trick 用到 logistic regression上. 从另一个角度来看soft-margin SVM,将其与 logistic regression进行对比 ...
- 【mysql】autocommit=0后,commit, rollback无效
之前在[mysql]MySQLdb中的事务处理中用autocommit和commit()以及rollback()实现了事务处理. 但后来,用同样的代码在另一个数据库中运行却失败了.找了一个下午的原因. ...
- Java字符串的操作
判断字符串是否存在 使用str.contains("values") public class one { /*判断某个字符串是否存在*/ public static void m ...
- websocket+Django+python+paramiko实现web页面执行命令并实时输出
一.概述 WebSocket WebSocket的工作流程:浏览器通过JavaScript向服务端发出建立WebSocket连接的请求,在WebSocket连接建立成功后,客户端和服务端就可以通过 T ...
- windows service程序的Environment.CurrentDirectory路径
当前工作目录Environment.CurrentDirectory,对于winform程序,其是在程序放置的目录里, 而windows service的Environment.CurrentDire ...
- Chakra调试笔记 TypedArray
一.TypedArray类型 TypedArray是漏洞中常见到的结构,手册用法有四 1.new TypedArray(length); //byteLength=length * sizeof(Ty ...
- python全栈开发day44-js、DOM、BOM
JS的三大部分 一.ECMAJavaScript基础语法: 1.javascript的引入方式 1) 行内式 <script> alert(1) </script> 2) 引入 ...
- HDU3038 How Many Answers Are Wrong 并查集
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - HDU3038 题意概括 有一个序列,共n个数,可正可负. 现在有m个结论.n<=200000,m< ...
- vi中批量加注释
用v进入virtual模式 按Control+v(win下面ctrl+q)进入列模式 上下键来进行选择 I进行输入(shift+i) 按两次ese键