【发布时间】: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