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)使用的更多相关文章

  1. ASP.NET Core中间件(Middleware)实现WCF SOAP服务端解析

    ASP.NET Core中间件(Middleware)进阶学习实现SOAP 解析. 本篇将介绍实现ASP.NET Core SOAP服务端解析,而不是ASP.NET Core整个WCF host. 因 ...

  2. ASP.NET Core 入门教程 9、ASP.NET Core 中间件(Middleware)入门

    一.前言 1.本教程主要内容 ASP.NET Core 中间件介绍 通过自定义 ASP.NET Core 中间件实现请求验签 2.本教程环境信息 软件/环境 说明 操作系统 Windows 10 SD ...

  3. ASP.NET Core 入门笔记10,ASP.NET Core 中间件(Middleware)入门

    一.前言 1.本教程主要内容 ASP.NET Core 中间件介绍 通过自定义 ASP.NET Core 中间件实现请求验签 2.本教程环境信息 软件/环境 说明 操作系统 Windows 10 SD ...

  4. ASP.NET Core 中间件Diagnostics使用

    ASP.NET Core 中间件(Middleware)Diagnostics使用.对于中间件的介绍可以查看之前的文章ASP.NET Core 开发-中间件(Middleware). Diagnost ...

  5. ASP.NET Core 中间件Diagnostics使用 异常和错误信息

    ASP.NET Core 中间件(Middleware)Diagnostics使用.对于中间件的介绍可以查看之前的文章ASP.NET Core 开发-中间件(Middleware). Diagnost ...

  6. ASP.NET Core 中间件自定义全局异常处理

    目录 背景 ASP.NET Core过滤器(Filter) ASP.NET Core 中间件(Middleware) 自定义全局异常处理 .Net Core中使用ExceptionFilter .Ne ...

  7. [转帖]ASP.NET Core 中间件(Middleware)详解

    ASP.NET Core 中间件(Middleware)详解   本文为官方文档译文,官方文档现已非机器翻译 https://docs.microsoft.com/zh-cn/aspnet/core/ ...

  8. 在ASP.NET Core使用Middleware模拟Custom Error Page功能

    一.使用场景 在传统的ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAtt ...

  9. [转]ASP.NET Core 中间件详解及项目实战

    本文转自:http://www.cnblogs.com/savorboard/p/5586229.html 前言 在上篇文章主要介绍了DotNetCore项目状况,本篇文章是我们在开发自己的项目中实际 ...

随机推荐

  1. Laravel 的文件存储 - Storage

    记录一下 Laravel Storage 的常见用法 内容写入磁盘文件 > php artisan tinker >>> use Illuminate\Support\Faca ...

  2. python接口自动化测试七:获取登录的Cookies,并关联到下一个请求

    获取登录的cookies:loginCookies = r.cookies 把获取到的cookies传入请求:cookies=loginCookies 此方法需每一次都调用登录方法,并且每一次发送请求 ...

  3. 方法名太多,使用方法的重载(overload)来解决

    package chapter04; /* 问题:方法名太多了,不容易记忆,有时会出错 使用方法的重载(overload)来解决 */public class C09_Method { public ...

  4. Redis数据结构之list

    一:介绍 1.存储list ArrayList使用数组的方式 LinkedList使用双向链接的方式 二:Redis客户端 1.左端与右端插入 2.左端查询 3.左端与右端弹出 4.长度 5.在头部插 ...

  5. python2与python3的差异

    最近在学习python3,遇到过几次python3与python2的的问题,python2使用,而到了python3就不适用了,就整理了一下自己到目前为止所遇到了几个问题(以下是小白见解) 1.pyt ...

  6. HDU 2089 不要62 【数位dp】

    <题目链接> 不要62 Problem Description 杭州人称那些傻乎乎粘嗒嗒的人为62(音:laoer).杭州交通管理局经常会扩充一些的士车牌照,新近出来一个好消息,以后上牌照 ...

  7. ImportError: cannot import name cbook

    Faster RCNN训练的时候,出现错误: from matplotlib import path, transforms File , in <module> from . impor ...

  8. P1356 数列的整数性

    P1356 数列的整数性打的骗分,在多组数据的情况下还能骗到分,可以了.又TMD是dp.f[i][j]表示+-第i个数能否达到%p后的余数j,如果f[n][0]==true就可以. #include& ...

  9. ios技术篇:导航栏push遵循的三个规则

    1.如果B视图有一个自定义的左侧按钮(leftBarButtonItem),则会显示这个自定义按钮 2.如果B没有自定义按钮,但是A视图的backBarButtonItem属性有自定义项,则显示这个自 ...

  10. scikit-learn全局图

    https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html