代码拉取完成,页面将自动刷新
class Program
{
static void Main(string[] args)
{
IApplicationBuilder appBuidler=new ApplicationBuilder(null);
appBuidler.UseMiddleware<LogMiddleWare>();
appBuidler.Use(async (context,next)=>{
await Console.Out.WriteLineAsync("Call before next.");
await next(context);
await Console.Out.WriteLineAsync("Call after next.");
});
appBuidler.Run(async (context)=>{
await Console.Out.WriteLineAsync("hello world!");
});
var app=appBuidler.Build();
var response=app.Invoke(new RequestContext(){ Url="http://localhost"});
response.Wait();
Console.ReadLine();
}
}
//LogMiddleWare类
public class LogMiddleWare
{
private readonly RequestDelegate _next;
public LogMiddleWare(RequestDelegate next)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
_next = next;
}
public async Task Invoke(RequestContext context){
await Console.Out.WriteLineAsync("before log!");
await _next(context);
await Console.Out.WriteLineAsync("after log!");
}
}
//RequestContext 类模拟了请求上下文
public class RequestContext
{
public string Url{ get; set;}
}
//RequestDelegate模拟了这一类请求的委托
public delegate Task RequestDelegate(RequestContext context);
//IApplicationBuilder用来创建注册委托和并创建应用
public interface IApplicationBuilder
{
IServiceProvider ApplicationServices{get;set;}
void Add(Func<RequestDelegate,RequestDelegate> middleware);
RequestDelegate Build();
}
//ApplicationBuilderExtension对IApplication进行了一些方法的扩展,UseMiddleWare,Use,Run等方法
void UseMiddleware<T>(this IApplicationBuilder builder, params object[] args)
void Use(this IApplicationBuilder builder,Func<RequestContext,RequestDelegate,Task> func)
void Run(this IApplicationBuilder builder,Func<RequestContext,Task> last)
static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseTestServer()
.Configure(app =>
{
app.UseMiddleware<LogMiddleWare>();
app.Use(async (context, next) => {
await Console.Out.WriteLineAsync(context.Url + "Call before next.");
await next(context);
await Console.Out.WriteLineAsync(context.Url + "Call after next.");
});
app.Run(async (context) => {
await Console.Out.WriteLineAsync("hello world!");
});
})
.Build()
host.Run();
Console.ReadLine();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。