1. 定義中間內(nèi)容
1.1 必須有一個(gè)RequestDelegate 委托用了進(jìn)入一個(gè)中間件
1.2 通過構(gòu)造函數(shù)設(shè)置這個(gè)RequestDelegate委托
1.3 必須有一個(gè)方法Task Invoke,在這個(gè)方法里編寫中間件內(nèi)容最后執(zhí)行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> /// 參數(shù) /// </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. 編寫一個(gè)擴(kuò)展方法用來添加到程序中
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(); }//擴(kuò)展方式添加 app.UserTestMiddleWare("this is test
param"); //直接添加中間件方式 app.Use((context, next) => { context.Response.WriteAsync("
this is test"); return next(); }); }
?
熱門工具 換一換