.NET7的第三个预览版发布了,同样带来了mini api的更新,这次带来了路由过滤器,与mvc版的action 过滤器相似。具体见https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-3/

  用官方的代码,跑不起来,这样那样的问题,比如下面的代码,直接报空引用的异常。

app.MapGet("/data0/{no}", (string no) =>
{
Console.WriteLine($"Get方法中:no={no}");
return new Data { No = no, Name = "test" + DateTime.Now };

}).AddFilter((RouteHandlerInvocationContext context, RouteHandlerFilterDelegate next) =>
{
var no = (string?)context.Parameters[0];
Console.WriteLine($"Get方法前:no={no}");
if (no != null && !no.StartsWith("NO"))
{
return new ValueTask<object?>("no is error!");
}
var result = next(context);
if (result.IsCompleted)
{
Console.WriteLine($"Get方法后:结果={result.Result}");
}
return result;
});

  经过一阵折腾,终于正常的跑了起来,需要把map的方法独立出来写才可以。同时这里使用了三种方式来使用过滤器,换汤不换药,本质一样。

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

Data GetData(string no)
{
Console.WriteLine($"Get方法中:no={no}");
return new Data { No = no, Name = "test" + DateTime.Now };
};
//第一种方式
app.MapGet("/data1/{no}", GetData)
.AddFilter((RouteHandlerInvocationContext context, RouteHandlerFilterDelegate next) =>
{
var no = (string?)context.Parameters[0];
Console.WriteLine($"Get方法前:no={no}");
if (no != null && !no.StartsWith("NO"))
{
return new ValueTask<object?>("no is error!");
}
var result = next(context);
if (result.IsCompleted)
{
Console.WriteLine($"Get方法后:结果={result.Result}");
}
return result;
});

string AddTest(Data data)
{
Console.WriteLine($"Post方法中:no={data.No}");
return "OK";
}
app.MapPost("/data1", AddTest)
.AddFilter((RouteHandlerInvocationContext context, RouteHandlerFilterDelegate next) =>
{
var data = (Data?)context.Parameters[0];
Console.WriteLine($"Post方法前:data={data}");
var result = next(context);
if (result.IsCompleted)
{
Console.WriteLine($"Post方法后:结果={result.Result}");
}
return result;
});
//第二种方式
app.MapGet("/data2/{no}", GetData)
.AddFilter((RouteHandlerContext routeHandlerContext, RouteHandlerFilterDelegate next) =>
{
return (context) =>
{
var no = (string?)context.Parameters[0];
if (no != null && !no.StartsWith("NO"))
{
return new ValueTask<object?>("no is error!");
}
return next(context);
};
});
//第三种方式
app.MapGet("/data3/{name}", GetData).AddFilter<MyFilter>();

app.Run();

public class MyFilter : IRouteHandlerFilter
{
public ValueTask<object?> InvokeAsync(RouteHandlerInvocationContext context, RouteHandlerFilterDelegate next)
{
var no = (string?)context.Parameters[0];
if (no != null && !no.StartsWith("NO"))
{
return new ValueTask<object?>("no is error!");
}
return next(context);
}
}

public record Data
{
public string No { get; set; }
public string Name { get; set; }
}

  想要更快更方便的了解相关知识,可以关注微信公众号 

.NET7之MiniAPI(特别篇):.NET7 Preview3_.NET7 Preview3