如何获取操作参数是FromServices或FromBody或其他

时间:2019-07-07 09:00:12

标签: c# asp.net-core asp.net-web-api .net-core asp.net-core-2.0

我有一个自定义操作过滤器,用于在执行操作之前检查操作参数

public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    if (context.ModelState.IsValid == false)
        throw new Exception("");
    if (context.ActionArguments.Values.Any() && context.ActionArguments.Values.All(v => v.IsAllPropertiesNull()))
        throw new Exception("");

    await next();
}

如何检查context.ActionArguments.Value[FromBody]还是[FromServices][FromRoute]等...

1 个答案:

答案 0 :(得分:2)

您从每个参数的BindingInfo获取绑定源。您是从context.ActionDescriptor.Parameters获得的。这是一个例子。

public class CustomActionFilter: IAsyncActionFilter
{
    /// <inheritdoc />
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        foreach (var parameterDescriptor in context.ActionDescriptor.Parameters)
        {
            var bindingSource = parameterDescriptor.BindingInfo.BindingSource;

            if (bindingSource == BindingSource.Body)
            {
                // bound from body
            }
            else if (bindingSource == BindingSource.Services)
            {
                // from services
            }
            else if (bindingSource == BindingSource.Query)
            {
                // from query string
            }
        }
    }
}