Search code examples
azureazure-functions.net-6.0middleware

Pass value between Middlewares in isolated Azure functions


I have had this issue on asp.net middleware for passing values between them and I used the request headers for setting and getting values inside middleware, but for the azure function, there is no request headers.

I can get request headers in this object context.BindingContext.BindingData but can not add new value as a result of IReadOnlyDictionary.

Here is my middlewares:

public class MiddlewareA : IFunctionsWorkerMiddleware
{
    public Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        // here I want calculate a value and pass it to MiddlewareB
        return next.Invoke(context);
    }
}

public class MiddlewareB : IFunctionsWorkerMiddleware
{
    public Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        // here I want get value from MiddlewareA
        return next.Invoke(context);
    }
}

And them in pipeline in this order:

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

        host. Run();

I use HttpTrigger and I want to know how can I pass the values between middleware.


Solution

  • I don't think there is request header in AZ Functions.

    Solution here is to use context.Items Dictionary.
    You would just pass your value to it in MiddlewareA

    context.Items["MyValue"] = myValue;
    

    And call it in the MiddlewareB like

    if (context.Items.TryGetValue("MyValue", out var value))
    { 
    //Do Something with value
    }