Azure-Functions icon indicating copy to clipboard operation
Azure-Functions copied to clipboard

Using Middleware with Azure Functions

Open vijayrkn opened this issue 1 year ago • 1 comments

Creating this issue on behalf of the Visual Studio customer. Please find the details of the issue here: https://developercommunity.visualstudio.com/t/Using-Middleware-with-Azure-Functions/10748527

vijayrkn avatar Sep 19 '24 21:09 vijayrkn

Dale Godfredson

Reported Sep 18, 2024 3:58 PM  Hi

I’d like to include middleware for my Azure function using the Isolated Worker Model. Currently using the latest version of .Net 8 & visual studio 2022.

As per the documentation (https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide?tabs=windows) it indicates to use ConfigureFunctionsWorkerDefaults however when I try to use this visual studio gives me the following error:

AZFW0014: The registration method for ‘ConfigureFunctionsWebApplication’ is expected for ASP.Net Core integration.

The example code is:

var host = new HostBuilder()
    . ConfigureFunctionsWorkerDefaults(workerApplication =>
    {
        // Register our custom middlewares with the worker

workerApplication.UseMiddleware<ExceptionHandlingMiddleware>();

workerApplication.UseMiddleware<MyCustomMiddleware>();

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

However I can get it to work adding a reference to ConfigureFunctionsWorkerDefaults after ConfigureFunctionsWebApplication as follows:

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

host. Run();

Can you please advise if this is the correct way to implement.

vijayrkn avatar Sep 19 '24 21:09 vijayrkn