Search code examples
.netazure-functionsmiddleware

Azure function middleware - Get response data before return to user


I want to retrieve data and format it before return to the user but don't know how to retrieve it, I see that the context only provides the request.

public class CustomResponse : IFunctionsWorkerMiddleware
    {
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            try
            {
                await next(context);
                if (!context.IsHttpTriggerFunction())
                {
                    return;
                }
                /// format response here
            } catch (Exception ex)
            {
                await context.CreateJsonResponse(System.Net.HttpStatusCode.InternalServerError, new
                {
                    errorMessage = ex.Message
                });
            }
        }
    }

Does FunctionContext support us to get response data? If yes, how can i get it?


Solution

  • After research, I think FunctionContext doesn't support us to get the data returned from the function, so I choose another way instead of middleware.

    I write a static function to convert object to json string

    private JsonSerializerOptions camelOpt = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        };
    
    public static string ToJsonString(this object input, bool camelCase = false) => JsonSerializer.Serialize(input, camelCase ? camelOpt : null);
    
    [Function(nameof(Temp))]
    public object Temp([HttpTrigger(AuthorizationLevel.Function,"get", "post", Route = ESignRoutes.Temp)]
         HttpRequestData req,
         FunctionContext context)
        {
            object data = null;
            //todo
            return data.ToJsonString(camelCase: true);
        }
    

    Besides, still need middleware to handle exception

    public class CustomResponse : IFunctionsWorkerMiddleware
    {
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            try
            {
                await next(context);
                if (!context.IsHttpTriggerFunction())
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                var message = ex.Message ?? " ";
                message = message.Replace("One or more errors occurred. (", "");
                message = message[..^1];
                await context.CreateJsonResponse(
                    System.Net.HttpStatusCode.InternalServerError,
                    new
                    {
                        error = new
                        {
                            message = message
                        }
                    });
            }
        }
    }