Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Per Bolmstedt 84 posts 380 karma points
    Dec 01, 2021 @ 12:17
    Per Bolmstedt
    0

    Better place than DefaultControllerType Index() to perform on-each-request actions in Umbraco 9 or ASP.NET Core

    For actions that need to run on each request, we have always put these in the Index() method of the DefaultControllerType and then hooked that controller up in the Umbraco Rendering Defaults Options (9) or using a composer (8).

    These on-each-request action are things like

    • Initializing a cookie that is used during execution
    • Redirecting based on circumstances (switch language, go directly to "my pages", ...)
    • Enriching the request pipeline with something based on the requesting user

    I'm wondering if there's a better way to inject these on-each-request actions in Umbraco 9 or using ASP.NET Core.

    The problem with the Default Controller approach, even if it works, is that

    • The DefaultControllerType Index() action becomes bloated
    • The DefaultControllerType Index() must be aware of all on-each-request actions
    • Any "filtering" to decide whether an on-each-request action is even applicable must be done as part of the action (i.e. an action that should only run for signed-in members)
    • If we don't use the default controller, all actions are gone

    I'm guessing there are Middleware-type ways of doing this in a different way, but I'm mostly interested in Umbraco-specific solutions, since all on-each-request actions will likely involve Umbraco.

    Thankful for any ideas.

  • Patrick de Mooij 72 posts 622 karma points MVP 3x c-trib
    Dec 01, 2021 @ 12:25
    Patrick de Mooij
    100

    You should still be able to use Umbraco code within custom middlewares. I also use it for a package to track 404 requests: https://github.com/patrickdemooij9/InboundLinkErrors/blob/v9/main/source/InboundLinkErrors.Core/MiddleWare/LinkErrorsMiddleware.cs

  • Per Bolmstedt 84 posts 380 karma points
    Dec 01, 2021 @ 12:44
    Per Bolmstedt
    0

    And if I understand correctly, you use a User Composer to add this middleware to the Umbraco pipeline:

    composition.Services.Configure<UmbracoPipelineOptions>(options => {
     options.AddFilter(new UmbracoPipelineFilter(
      "InboundLinkErrors",
      applicationBuilder => { },
      applicationBuilder => {
       applicationBuilder.UseMiddleware<LinkErrorsMiddleware>(); },
      applicationBuilder => { } )); });
    

    Should I do the same even though not building a package?

  • Patrick de Mooij 72 posts 622 karma points MVP 3x c-trib
    Dec 01, 2021 @ 15:21
    Patrick de Mooij
    1

    Yes, but in my example I load it after all the Umbraco middleware has finished. I am not quite sure when you want it loaded though.

Please Sign in or register to post replies

Write your reply to:

Draft