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

Posted

技术标签:

【中文标题】如何将自定义对象从异步操作过滤器传递到 ASP.net 核心中的控制器?【英文标题】:How do I pass an custom object from an async action filter to a controller in ASP.net core? 【发布时间】: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();
    

【问题讨论】:

【参考方案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动作过滤器之前,模型绑定已经完成,需要默认构造函数来创建模型的实例。

【讨论】:

以上是关于如何将自定义对象从异步操作过滤器传递到 ASP.net 核心中的控制器?的主要内容,如果未能解决你的问题,请参考以下文章

动作必须是普通对象。将自定义中间件用于异步功能。反应原生

将自定义数据从 Jersey Filter 服务传递到 Jersey End-Point 服务

Android将自定义对象从服务传递给活动

如何将自定义信息从 App Engine Authenticator 传递到 Endpoint?

从视图中,如何将自定义“选择”传递到表单的 ChoiceField?

动作必须是普通对象。将自定义中间件用于测试库而不是应用程序上的异步操作