简体   繁体   English

是否可以在 Azure Functions 中的每个函数开始运行之前运行代码?

[英]Is it possible to run code before every function starts running in Azure Functions?

Currently, I'm executing a bunch of code (such as validating query/header parameters as well as authenticating the user) in every function manually:目前,我正在每个函数中手动执行一堆代码(例如验证查询/标头参数以及验证用户):

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

   // Step 1 - Validate input

   // Step 2 - Process request

}

But I'd like to refactor Step 1 out so that it doesn't appear inside each function.但我想重构第 1 步,以便它不会出现在每个函数中。 Is it possible to write an attribute or some kind of pre-request logic that takes the HttpRequestMessage and returns a HttpResponseMessage (such as BadRequest ) based on validation outcome?是否可以编写一个属性或某种类型的预请求逻辑,该逻辑接受HttpRequestMessage并根据验证结果返回HttpResponseMessage (例如BadRequest )?

One option is to use a (currently) preview feature of AzureFunctions named FunctionFilters一种选择是使用名为FunctionFilters的 AzureFunctions 的(当前)预览FunctionFilters

Sample copied (and shortened) from official docs:从官方文档复制(和缩短)的示例:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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