.Net Core 创建和使用中间件
2024-08-31 07:33:43
1. 定义中间内容
1.1 必须有一个RequestDelegate 委托用了进入一个中间件
1.2 通过构造函数设置这个RequestDelegate委托
1.3 必须有一个方法Task Invoke,在这个方法里编写中间件内容最后执行RequestDelegate委托
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace Haos.Develop.CoreTest
{
public class TestMiddleware
{
protected RequestDelegate Next; /// <summary>
/// 参数
/// </summary>
public string Str { get; set; } public TestMiddleware(RequestDelegate next,string s)
{
Next = next;
Str = s;
} public virtual Task Invoke(HttpContext context)
{
context.Response.WriteAsync("this is test string");
return Next(context);
}
}
}
2. 编写一个扩展方法用来添加到程序中
using Haos.Develop.CoreTest.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace Haos.Develop.CoreTest
{
public static class Extension
{
public static IApplicationBuilder UserTestMiddleWare(this IApplicationBuilder app, string str)
{
return app.UseMiddleware<TestMiddleware>(str);
}
}
}
3. 在Startup添加中间件
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//扩展方式添加
app.UserTestMiddleWare("this is test param");
//直接添加中间件方式
app.Use((context, next) =>
{
context.Response.WriteAsync("this is test");
return next();
});
}
最新文章
- 开窗函数 First_Value 和 Last_Value
- ACM 兰州烧饼
- RTO &; RPO
- 九 spring和mybatis整合
- RFS一些基本概念
- 如果解决ubuntu tab键不能提示命令
- Javascript的四种继承方式
- flex中DataGrid里使用itemRenderer后数据无法绑定到数据源的问题
- oracle 11g ora-01843 无效月份
- OpenCV学习笔记:矩阵的掩码操作
- 【设计模式 - 2】之单例模式(Singleton)
- UVALIVE 5893 计算几何+搜索
- [每日一题] OCP1z0-047 :2013-07-25 权限――角色与对象权限
- 去空格 whitespaceAndNewlineCharacterSet
- BZOJ 2795: [Poi2012]A Horrible Poem( hash )
- Thrift总结(二)创建RPC服务
- Event Sourcing pattern
- Java线程基础(二)
- 常用算法和Demo(Java实现)(持续更新)
- Codeforces 359E Neatness