简体   繁体   中英

Azure Functions Runtime v3 Middleware

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM