【问题标题】:How to modify ViewComponent result in ASP.NET Core 3.1如何在 ASP.NET Core 3.1 中修改 ViewComponent 结果
【发布时间】: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 后拦截呼叫时,很难实现。但是在调用InvokeAsyncInvoke 之前或调用之后(使用IViewComponentResult 运行)返回IHtmlContent,您可以有一个相当简单的解决方案。
  • 我想在返回IViewComponentResult后拦截调用。
  • 是的,由于我在第一条评论中分享的源代码中的默认调用程序实现,这很难。请注意,在返回IViewComponentResult 之后意味着您可以获得该结果(通过拦截)。该结果将被执行,您将获得最终的IHtmlContent,可以通过拦截IViewComponentHelper.InvokeAsync获得。

标签: asp.net-core filter asp.net-core-3.1 asp.net-core-viewcomponent


【解决方案1】:

不支持直接拦截 ViewComponents,因为它不参与请求管道。来自official doc

一个视图组件类:

  • 不参与控制器生命周期,这意味着您不能在视图组件中使用过滤器

但您可以改为通过invoking the ViewComponent from an Action 间接执行此操作。然后用你的过滤器装饰动作:

[BeforeCheckoutCall]
public IActionResult Checkout()
{
    return ViewComponent("PriorityList", new { maxPriority = 3, isDone =     false });
}

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 2021-10-27
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多