DotNETWeekly-io / DotNetWeekly

DotNet weekly newsletter
MIT License
198 stars 3 forks source link

【文章推荐】ASP.NET Core 中的短路 #651

Closed gaufung closed 1 month ago

gaufung commented 1 month ago

https://dev.to/moh_moh701/introduction-to-shortcircuit-and-mapshortcircuit-in-net-8-12ml

gaufung commented 1 month ago

image

ASP.NET Core 中每个请求的处理流程如下:

ASP.NET Core 8 中引入的 Short Circuit。顾名思义,我们定义好一些请求可以不用经过各种 Middleware 而直接处理并且返回,比如像一些静态文件处理,我们可以直接返回结果,通常是为了下述考虑:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<CustomerMiddleware>();
app.MapGet("/shortcircuit", () => "Hello From Short Circuit").ShortCircuit();
app.Run();

class CustomerMiddleware
{
    private readonly RequestDelegate _next;

    public CustomerMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public Task Invoke(HttpContext context)
    {
        System.Console.WriteLine("Customer Middleware");
        return _next(context);
    }
}

当我们访问 shortcircuit 路径的时候,CustomerMiddleware 并不会执行。除此之外,还有 MapShortCircuit 拓展方法

app.MapShortCircuit(500, "robots.txt", "favicon.ico");

这里定义了所有访问 robots.txtfavicon.ico 路径的请求都会返回 500.