Share via

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

梁捷廷/JT 1 Reputation point
2022-03-07T08:30:13.603+00:00

在.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");
        }
    }
}
Developer technologies | ASP.NET Core | Other
0 comments No comments

2 answers

Sort by: Most helpful
  1. Anonymous
    2022-03-08T03:12:33.727+00:00

    Hi JT-7107 ,

    As Bruce said, the filter is used for MVC controller not minimal API, you could check this github issue, it seems asp.net core team is talk about how to add filter inside this minimal API and it seems will add it at asp.net 7.

    Was this answer helpful?

    0 comments No comments

  2. Bruce (SqlWork.com) 84,071 Reputation points
    2022-03-07T16:18:03.94+00:00

    action filters are for controller actions. the call to the folder is done the controller dispatcher. MapGet() does not have Action Filter support.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.