Jens Roderus
Jens Roderus

Reputation: 201

Use Azure Function middleware only for selected functions

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?

Upvotes: 4

Views: 2200

Answers (2)

Sil
Sil

Reputation: 1330

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();

Upvotes: 0

Jens Roderus
Jens Roderus

Reputation: 201

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.

Upvotes: 3

Related Questions