3

I have a project with several Azure Functions and in the Main function where the startup is configured I register middleware like this:

var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults(builder =>
            {
                builder.UseMiddleware<MyMiddleware>();
            })

This cause the middleware to be used on all functions, whether they are time triggered or HTTP request triggered. I want to be able to exclude the middleware for certain functions, or for all time triggered functions. Is this possible and how would one do it?

Jens Roderus
  • 181
  • 9

2 Answers2

2

I seem to have found my answer here: github.com/Azure/azure-functions-dotnet-worker/issues/855

Summary: Not supported yet. But in Version 1.8.0-preview1 of Microsoft.Azure.Functions.Worker it is possible to use middleware conditionally.

Jens Roderus
  • 181
  • 9
  • Now an update is available where UseMiddleware can be replaced with UseWhen to achieve the conditional usage I was after. – Jens Roderus Sep 09 '22 at 12:14
0

An example from the Microsoft docs to complete the answer:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults(workerApplication =>
    {
        workerApplication.UseWhen<StampHttpHeaderMiddleware>((context) =>
        {
            // We want to use this middleware only for http trigger invocations.
            return context.FunctionDefinition.InputBindings.Values
                          .First(a => a.Type.EndsWith("Trigger")).Type == "httpTrigger";
        });
    })
    .Build();
Sil
  • 1,120
  • 1
  • 9
  • 30