【发布时间】:2021-04-01 07:35:24
【问题描述】:
我想像使用 MVC ActionFiltersAttribute 一样使用过滤器来修改 ViewComponent 的结果。我试过ActionFilterAttribute,但它不能与ViewComponent 一起工作,即使它没有调用。
public class BeforeCheckoutCallFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
if (context.RouteData.Values["action"].ToString().Equals("ProductDetails_AttributeChange", StringComparison.InvariantCultureIgnoreCase))
{
//Business logic
}
return;
}
}
我在 Startup.cs 中注册了这个过滤器
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add<BeforeCheckoutCallFilter>();
}
}
有没有办法获得 ViewComponent 结果并像我们过去使用 MVC 过滤器那样对其进行修改?
更新:返回IViewComponentResult后想拦截通话。
注意:我知道ViewComponent 不参与控制器生命周期,这意味着我们不能在视图组件中使用过滤器。
【问题讨论】:
-
您可以拦截视图组件调用以获取其结果
IHtmlContent或在调用它之前,但看起来很难获得IViewComponentResult(您的视图组件返回的直接结果)。默认调用程序是DefaultViewComponentInvoker没有可拦截IViewComponentResult的扩展点,如您在此处看到的github.com/dotnet/aspnetcore/blob/… - 除非您将那里的代码复制到您的自定义视图组件调用程序类中。 -
我不想更改 ViewComponent。我想拦截它。
-
当你将它与动作过滤器进行比较时,我认为它需要能够拦截
IViewComponentResult。可以在各个点进行拦截,因此无法准确说出您想要什么。正如我所评论的,在返回IViewComponentResult后拦截呼叫时,很难实现。但是在调用InvokeAsync或Invoke之前或调用之后(使用IViewComponentResult运行)返回IHtmlContent,您可以有一个相当简单的解决方案。 -
我想在返回IViewComponentResult后拦截调用。
-
是的,由于我在第一条评论中分享的源代码中的默认调用程序实现,这很难。请注意,在返回
IViewComponentResult之后意味着您可以获得该结果(通过拦截)。该结果将被执行,您将获得最终的IHtmlContent,可以通过拦截IViewComponentHelper.InvokeAsync获得。
标签: asp.net-core filter asp.net-core-3.1 asp.net-core-viewcomponent