Asp.Net Core中Filter大概有五种类型,分别为:authorization filter, resource filter, action filter, exception filter and result filter.
并且所有的filter一般都有同步版本和异步版本:IActionFilter, IAsyncActionFilter
这些filter有什么作用呢:ExceptionFilter可以让程序在发生exception时执行的代码,同样ActionFilter就是程序在执行Controller下面Action的时候执行的代码。比如在执行action之前统一做一下判断。
这里记录ExceptionFilter 和ActionFilter的简单代码片段:
MyExceptionFilter.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace WebApi
{
public class MyExceptionFilter : IAsyncExceptionFilter
{
public Task OnExceptionAsync(ExceptionContext context)
{
context.Result = new ObjectResult(new { code = 500, message = "Error" });
return Task.CompletedTask;
}
}
}
MyActionFilter.cs
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
namespace WebApi
{
public class MyActionFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
Console.WriteLine("before execute");
// ControllerActionDescriptor ctrActionDes = context.ActionDescriptor as ControllerActionDescriptor; get some infomation in filter.
ActionExecutedContext r = await next();
if (r.Exception == null)
{
Console.WriteLine("no exception");
}
else
{
Console.WriteLine("Exception occur");
}
}
}
}
然后在Program.cs文件里注册对应的filter:
builder.Services.Configure<MvcOptions>(options =>
{
options.Filters.Add<MyExceptionFilter>();
});
builder.Services.Configure<MvcOptions>(opt =>
{
opt.Filters.Add<MyActionFilter>();
});
完整的Program.cs文件:
using Microsoft.AspNetCore.Mvc;
namespace WebApi
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.Configure<MvcOptions>(options =>
{
options.Filters.Add<MyExceptionFilter>();
});
builder.Services.Configure<MvcOptions>(opt =>
{
opt.Filters.Add<MyActionFilter>();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}