Home > Software design >  How to register action filter in .NET 6
How to register action filter in .NET 6

Time:05-16

I have this validation filter class.

public class ValidationFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        if (!context.ModelState.IsValid)
        {
            var errorsInModelState = context.ModelState
                .Where(x => x.Value?.Errors.Count > 0)
                .ToDictionary(kvp => kvp.Key, kvp => kvp.Value?.Errors.Select(x => x.ErrorMessage)).ToArray();

            var errorResponse = new ErrorResponse();

            foreach (var error in errorsInModelState)
            {
                foreach (var subError in error.Value)
                {
                    var errorModel = new Error
                    {
                        FieldName = error.Key,
                        Message = subError
                    };

                    errorResponse.Errors.Add(errorModel);
                }
            }

            context.Result = new BadRequestObjectResult(errorResponse);
            return;
        }
        await next();
    }
}

In ASP.NET 5, we add ValidationFilter like below

        services
            .AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
                options.Filters.Add<ValidationFilter>();
            })
            .AddFluentValidation(mvcConfiguration => mvcConfiguration.RegisterValidatorsFromAssemblyContaining<Startup>())
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

How to I add it at Program.cs in .NET 6?

CodePudding user response:

In .Net6, We use builder.Services.AddControllersWithViews() instead of services.AddMvc(). So you can just set like this:

builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<ValidationFilter>();
});

More about .NET 6 new configuration can refer to this link.

CodePudding user response:

You can define a class which inherited from ActionFilterAttribute that adds a header to the response as per the below sample code:

public class ResponseHeaderAttribute : ActionFilterAttribute
{
    private readonly string _name;
    private readonly string _value;

    public ResponseHeaderAttribute(string name, string value) =>
        (_name, _value) = (name, value);

    public override void OnResultExecuting(ResultExecutingContext context)
    {
        context.HttpContext.Response.Headers.Add(_name, _value);

        base.OnResultExecuting(context);
    }
}

Then you can add the filter in your Program.cs file (based on dot net 6 new console template):

builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<ResponseHeaderAttribute>();
});

Now you can use it in your controllers for example:

[ResponseHeader("my-filter", "which has the value")]
public IActionResult DoSomething() =>
    Content("I'm trying to do something");
  • Related