是否可以在每个功能开始在Azure Functions中运行之前运行代码?

时间:2018-11-12 16:00:43

标签: c# validation httprequest azure-functions

目前,我正在每个函数中手动执行一堆代码(例如,验证查询/标头参数以及验证用户身份):

[FunctionName( "functionname" )]
public static async Task<HttpResponseMessage> Run( [HttpTrigger( AuthorizationLevel.Anonymous, "post")]HttpRequestMessage req)
{

   // Step 1 - Validate input

   // Step 2 - Process request

}

但是我想将步骤1重构出来,以便它不会出现在每个函数中。

是否可以编写一个属性或某种预请求逻辑,使其采用HttpRequestMessage并根据验证结果返回HttpResponseMessage(例如BadRequest)?

1 个答案:

答案 0 :(得分:0)

一种选择是使用名为FunctionFilters的AzureFunctions的(当前)预览功能

从官方文档中复制(并缩短)的样本:

public static class Functions
{
    [WorkItemValidator]
    public static void ProcessWorkItem(
        [QueueTrigger("test")] WorkItem workItem)
    {
        Console.WriteLine($"Processed work item {workItem.ID}");
    }
}

public class WorkItemValidatorAttribute : FunctionInvocationFilterAttribute
{
    public override Task OnExecutingAsync(
        FunctionExecutingContext executingContext, CancellationToken cancellationToken)
    {
        executingContext.Logger.LogInformation("WorkItemValidator executing...");

        var workItem = executingContext.Arguments.First().Value as WorkItem;
        string errorMessage = null;
        if (!TryValidateWorkItem(workItem, out errorMessage))
        {
            executingContext.Logger.LogError(errorMessage);
            throw new ValidationException(errorMessage);
        }

        return base.OnExecutingAsync(executingContext, cancellationToken);
    }

    private static bool TryValidateWorkItem(WorkItem workItem, out string errorMessage)
    {
        // your validation logic goes here...
    }
}

您可以在此处找到更多信息: https://github.com/Azure/azure-webjobs-sdk/wiki/Function-Filters