Search code examples
asp.net-coreasp.net-core-middlewarepiranha-cms

Piranha CMS middleware to capture requests to /uploads


When a request is made for an image|file it doesn't reach my middleware.

I can see that when UseCms is called it adds PiranhaStartupFilter

serviceBuilder.Services.AddTransient<IStartupFilter, PiranhaStartupFilter>();

Which adds UseStaticFiles() to the ApplicationBuilder.

public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
    return builder =>
    {
        builder
            .UseSecurityMiddleware()
            .UseStaticFiles()
            .UseMiddleware<RoutingMiddleware>()
            .UseMiddleware<SitemapMiddleware>();
        next(builder);
    };
}

How could I overwrite this functionality so that my middleware is called for requests?

I'm expecting a call to /uploads/foo.jpg would be picked up in the InvokeAsync method of my middleware, registered like so:

app.UsePiranha(options =>
{
    options.Builder.CustomImageTools();
});

At present only files & favicon requests reach the InvokeAsync method in my middleware.


Solution

  • As middleware in asp.net is executed in the order they are added into the pipeline it should be sufficient to add your interceptor before making any calls to Piranha.

    You can add the middleware by adding a service above the call to UseCms() in startup.cs.

    services.AddPiranha(options =>
    {
        options.CustomImageFilter();
        options.UseCms();
    }
    
    public class CustomImageFilter : IStartupFilter
    {
        public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
        {
            return app =>
            {
                app.UseWhen(
                    context => some_condition,
                    appbuilder => appbuilder.CustomImageTools()
                );
                // Call the next configure method
                next(app);
            };
        }
    }