.NET6的mini api中,一个接口中,如何使用ActionFilterAttribute拦截器

Copper Contributor

在.NET6的mini api中,一个接口中,如何使用ActionFilterAttribute拦截器

例如,如下图,我定义了一个拦截器Filter,然后在我的接口GetWeatherForecast如代码中使用,但是这个拦截器好像并不会生效

 

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/weatherforecast",[Filter]() =>
{
    var forecast = new {title="测试"};
    return forecast;
})
.WithName("GetWeatherForecast");

app.Run();

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

public class Filter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        //拦截全局里是否带了token
        if (string.IsNullOrEmpty(context.HttpContext.Request.Query["token"]))
        {
            context.Result = new JsonResult("没有token");
        }
    }
}

 

 

1 Reply

HI @Dong_Yan,

Thanks for posting your issue here.

However this platform is used for how-to discussions and sharing best practices for building any app with .NET.Since your issue is a technical question, welcome to post it in Microsoft Q&A forum, the support team and communities on Microsoft Q&A will help you for any technical questions.
Besides, it will be appreciated if you can share it here once you post this technical question Microsoft Q&A.
Best Regards,
Lan Huang