如何将自定义对象从异步操作过滤器传递到 ASP.net 核心中的控制器?

How do I pass an custom object from an async action filter to a controller in ASP.net core?

我一直没能找到这个问题的好答案,或者它是否可能。我想这样做,以便我的 filter 使用 context.ActionArguments["personService"] = personService. 添加 object 作为 parameter 我可以使用 string type 进行论证,但是当我尝试使用自定义对象时,我不断使用 postman.

获得 415 error

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

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();
    }

您必须进行一些更改才能工作。首先,更改 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 动作过滤器之前,模型绑定已经完成,需要默认构造函数来创建模型实例。