我正在学习代理异步和等待。我得到了委托的想法,它就像一个函数指针,可以很好地理解简单的委托。我也在做一些实用的lambda。如果指出我从一个站点获得的代理中的执行流程,我将非常感激。
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
namespace Builder.Filtering.Web
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Use(next => context => FilterAsync(context, next));
app.Run(HelloWorldAsync);
}
public async Task FilterAsync(HttpContext context, RequestDelegate next)
{
var body = context.Response.Body;
var buffer = new MemoryStream();
context.Response.Body = buffer;
try
{
context.Response.Headers["CustomHeader"] = "My Header";
await context.Response.WriteAsync("Before\r\n");
await next(context);
await context.Response.WriteAsync("After\r\n");
buffer.Position = 0;
await buffer.CopyToAsync(body);
}
finally
{
context.Response.Body = body;
}
}
public async Task HelloWorldAsync(HttpContext context)
{
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello world\r\n");
}
public static void Main(string[] args)
{
var config = new ConfigurationBuilder().AddCommandLine(args).Build();
var host = new WebHostBuilder()
// We set the server by name before default args so that command line arguments can override it.
// This is used to allow deployers to choose the server for testing.
.UseKestrel()
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
问题
我的理解是,首先调用FilterAsync
,然后调用HelloWorldAsync
。但是如何知道何时致电HelloWorldAsync
?另外,await next(context);
的作用是什么?
我不是在寻找对.net核心的深刻理解。这只是了解委托流程的一个示例。