如何获取操作参数是 FromServices 或 FromBody 或其他
How to get action argument is FromServices or FromBody or another
我有一个自定义操作过滤器,用于在执行操作之前检查操作参数
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]
等等...
您从每个参数的 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
}
}
}
}
我有一个自定义操作过滤器,用于在执行操作之前检查操作参数
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]
等等...
您从每个参数的 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
}
}
}
}