Azure Functions Runtime v3 Middleware

Viewed 2322

Is there a way to access the request and response object in an azure middle ware.

Using a tutorial for a logging middleware I already got this far:

public class ExceptionLoggingMiddleware : IFunctionsWorkerMiddleware
{
    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        try
        {
            // Code before function execution here
            await next(context);
            // Code after function execution here
        }
        catch (Exception ex)
        {
            var log = context.GetLogger<ExceptionLoggingMiddleware>();
            log.LogWarning(ex, string.Empty);
        }
    }
}

but I want to access the response and request object too. Like status code, body parameters, query parameters etc. Is this possible?

1 Answers

While there is no direct way to do this, but there is a workaround for accessing HttpRequestData (Not the best solution but it should work until there is a fix.):

public static class FunctionContextExtensions
{
    public static HttpRequestData GetHttpRequestData(this FunctionContext functionContext)
    {
        try
        {
            KeyValuePair<Type, object> keyValuePair = functionContext.Features.SingleOrDefault(f => f.Key.Name == "IFunctionBindingsFeature");
            object functionBindingsFeature = keyValuePair.Value;
            Type type = functionBindingsFeature.GetType();
            var inputData = type.GetProperties().Single(p => p.Name == "InputData").GetValue(functionBindingsFeature) as IReadOnlyDictionary<string, object>;
            return inputData?.Values.SingleOrDefault(o => o is HttpRequestData) as HttpRequestData;
        }
        catch
        {
            return null;
        }
    }
}

And you can use it like this:

public class CustomMiddleware : IFunctionsWorkerMiddleware
{
    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        HttpRequestData httpRequestData = context.GetHttpRequestData();

        // do something with httpRequestData

        await next(context);
    }
}

Check out this for more details.

For Http Response, there is no workaround AFAIK. Further, check out GH Issue#530, that says that documentation for this will be added soon. This capability looks like a popular demand and expected to be fixed soon (at the time of writing this).

Related