Azure 函数中间件 - 在 return 之前获取响应数据给用户

Azure function middleware - Get response data before return to user

我想在 return 之前检索数据并将其格式化给用户,但不知道如何检索它,我看到上下文只提供了请求。

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

FunctionContext支持我们获取响应数据吗?如果是,我怎样才能得到它?

经过研究,我认为FunctionContext不支持我们获取函数返回的数据,所以我选择了另一种方式而不是中间件。

我编写了一个静态函数来将对象转换为 json 字符串

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

此外,还需要中间件来处理异常

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