【问题标题】:How do I pass an custom object from an async action filter to a controller in ASP.net core?如何将自定义对象从异步操作过滤器传递到 ASP.net 核心中的控制器?
【发布时间】:2021-10-02 14:31:14
【问题描述】:

我还没有找到一个很好的答案来解决这个问题,或者它是否可能。我想让我的filter 使用context.ActionArguments["personService"] = personService. 添加object 作为parameter 我可以使用string type 进行参数,但是当我尝试使用自定义对象时继续使用postman 获取415 error

我知道我可以使用context.HttpContext.Items.Add("personService",personService) 传递一个对象,但这对于我正在做的事情来说并不是一个优雅的解决方案。我有一个课程如下:

public class PersonService
    {
        private readonly string _name;
        private readonly int _age;
        private readonly string _location;
        public Person(string name, int age, string location)
        {
            _name = name;
            _age = age;
            _location = location;
        }

        public string printPerson(){
            return "name: {0} age: {1} location {2}", _name, _age, _location";
        }
    }

然后我的过滤器如下所示:

public class PersonFilterAttribute: Attribute, IAsyncActionFilter
    {
        public PersonFilterAttribute()
        {
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
           context.ActionArguments["personService"] = new PersonService("Thomas", 29,"Miami");

          
          await next();
        }
    }
 [HttpGet("personService")]
 [ServiceFilter(typeof(PersonFilterAttribute))]
 public async Task<string> passTheObject(Person person)
    {
          return person.printPerson();
    }

【问题讨论】:

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


    【解决方案1】:

    您必须进行一些更改才能正常工作。首先,更改 API 以添加属性 [FromQuery] 以指定 complex type 参数的来源(默认情况下,路由数据和查询字符串值仅用于简单类型)。

    [HttpGet("personService")]
    [ServiceFilter(typeof(PersonFilterAttribute))]
    public async Task<string> passTheObject([FromQuery] Person person)
    {
        return person.printPerson();
    }
    

    接下来您必须将无参数构造函数添加到模型Person

    public class Person {
        private readonly string _name;
        private readonly int _age;
        private readonly string _location;
    
        public Person() {
        }
    
        public Person(string name, int age, string location) {
            _name = name;
            _age = age;
            _location = location;
        }
    
        public string printPerson() {
            return string.Format("name: {0} age: {1} location {2}", _name, _age, _location);
        }
    }
    

    由于在执行OnActionExecution动作过滤器之前,模型绑定已经完成,需要默认构造函数来创建模型的实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 2023-03-19
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      相关资源
      最近更新 更多