【问题标题】:How can we implement multiple custom action filters in web api?我们如何在 web api 中实现多个自定义操作过滤器?
【发布时间】:2022-02-09 18:03:16
【问题描述】:

我们如何在 web api 中实现多个自定义操作过滤器?

public class FileValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            context.Result = new ValidationFailedResult(context.ModelState);
        }
    }
}

public class ModelStateFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            throw new ApiException(context.ModelState);
        }
    }
}

【问题讨论】:

  • 您可以将[FileValidation][ModelStateFilter]加在一起。

标签: asp.net-mvc api asp.net-mvc-4 asp.net-core-webapi


【解决方案1】:

要实现这一点,您需要在services (Dependency Injection) 中注册这些属性。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    .
    .
    services.AddScoped<FileValidationAttribute>();
    services.AddScoped<ModelStateFilterAttribute>();
    .
    .
}

使用ServiceFilter 属性在同一个动作方法中调用两个过滤器。

控制器

[HttpGet("TestAction")]
[ServiceFilter(typeof(FileValidationAttribute))]
[ServiceFilter(typeof(ModelStateFilterAttribute))]
public async Task<IActionResult> TestAction()
{
    return StatusCode((int)HttpStatusCode.OK);
}

参考这个链接了解ServiceFilter属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2012-06-12
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多