我可以将操作筛选器中的参数传递给控制器,特别是通过参数传递(在ASP.NET Core中)吗?
例如:
public class CategoryController : Controller
{
[HttpGet]
[ServiceFilter(typeof(ApiFilter))]
public async Task<IActionResult> Index(string dataComingFromActionFilter)
{
//use dataComingFromActionFilter
}
}
还有
public class ApiFilter: IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
//maybe something similar to
context.sendToActionAsArgument['dataComingFromActionFilter'] = "data";
}
}
答案 0 :(得分:2)
您可以使用
context.ActionArguments["dataComingFromActionFilter"] = "data";
用于更新现有操作参数。如果您需要添加新参数,那么
context.ActionArguments.Add("dataComingFromActionFilter", "data");
然后您可以通过Controller Action来实现
答案 1 :(得分:0)
在属性中将值设置为HttpContext的Items集合:
context.HttpContext.Items.Add("DataFromAttribute", date);
然后在控制器中以相同的方式读取它们:
this.HttpContext.Items["DataFromAttribute"];
答案 2 :(得分:0)
尝试使用下面的代码看看它是否有效。
public class PersonFilterAttribute: Attribute, IAsyncActionFilter
{
public PersonFilterAttribute()
{
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
context.ActionArguments.Add("personService", new PersonService("Thomas", 29,"Miami");
await next();
}
}
And In the controller read them in the same way:
this.HttpContext.Items["personService"];