【问题标题】:Setting [BindNever] during the action execution filter flow在动作执行过滤器流程中设置 [BindNever]
【发布时间】:2022-01-23 05:49:56
【问题描述】:

有谁知道我如何在ActionDescriptor.Parameters 上标记一个参数,使其行为方式类似于 [BindNever] 的行为方式?

我希望始终从特定类型中排除特定参数,而不在控制器上继续装饰它。

基本上我希望能够以某种方式将我的注入添加到我的函数中,这与它使用 CancellationToken 的方式相似

    public class TestController : ControllerBase
    {
        [HttpGet(Name = "Get")]
        public IActionResult Get([BindNever] IInjectedInterface injected)
        {
            //Injected can be used in this method

            return Ok();
        }

        [HttpPost(Name = "Post")]
        public IActionResult Post([BindNever] IInjectedInterface injected, FormModel formModel)
        {
            //Injected doesn't work here. There is an error that 

            /*System.InvalidOperationException: 'Action 'WebApplication3.Controllers.TestController.Post (WebApplication3)'
             has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be bound from body. 
            Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to specify bound from route, 
            and 'FromBodyAttribute' for parameters to be bound from body:
            IInjectedInterface injected
            FormModel formModel'
            */

            return Ok();
        }
    }



public class ActionExecutionFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var injectedParam = context.ActionDescriptor.Parameters.SingleOrDefault(x => x.ParameterType == typeof(IInjectedInterface));
        if (injectedParam != null)
        {
            context.ActionArguments[injectedParam.Name] = new Injected(99);
        }

        await next.Invoke();
    }

    private class Injected : IInjectedInterface
    {
        public Injected(int someData)
        {
            SomeData = someData;
        }

        public int SomeData { get; }
    }
}

【问题讨论】:

  • 您能否发布一些代码来解释有关您要排除哪个参数的更多详细信息?
  • 我更新了帖子。感谢您的支持

标签: filter binding asp.net-core-mvc


【解决方案1】:

我能够解决它。显然,您需要在 program.cs 中添加以下行以避免与模型绑定器相关的错误。

options.ModelMetadataDetailsProviders.Add(
    new ExcludeBindingMetadataProvider(typeof(IInjectedInterface)));

options.ModelMetadataDetailsProviders.Add(
    new BindingSourceMetadataProvider(typeof(IInjectedInterface), BindingSource.Special));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多