C# 是否可以在Azure函数中开始运行每个函数之前运行代码?
目前,我正在每个函数中手动执行一系列代码(例如验证查询/头参数以及验证用户):C# 是否可以在Azure函数中开始运行每个函数之前运行代码?,c#,validation,httprequest,azure-functions,C#,Validation,Httprequest,Azure Functions,目前,我正在每个函数中手动执行一系列代码(例如验证查询/头参数以及验证用户): [FunctionName( "functionname" )] public static async Task<HttpResponseMessage> Run( [HttpTrigger( AuthorizationLevel.Anonymous, "post")]HttpRequestMessage req) { // Step 1 - Validate input // Step
[FunctionName( "functionname" )]
public static async Task<HttpResponseMessage> Run( [HttpTrigger( AuthorizationLevel.Anonymous, "post")]HttpRequestMessage req)
{
// Step 1 - Validate input
// Step 2 - Process request
}
[FunctionName(“FunctionName”)]
公共静态异步任务运行([HttpTrigger(AuthorizationLevel.Anonymous,“post”)]HttpRequestMessage请求)
{
//步骤1-验证输入
//步骤2-处理请求
}
但是我想重构步骤1,这样它就不会出现在每个函数中。是否可以编写一个属性或某种请求前逻辑,以获取HttpRequestMessage
,并根据验证结果返回HttpResponseMessage
(例如BadRequest
),其中一个选项是使用名为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...
}
}
您可以在此处找到更多信息:
感谢信的可能副本。我们可以返回HttpResponseMessage而不是抛出ValidationException吗?由于方法的返回类型是Task,FunctionExecutionContext不提供任何功能性,我假设您不能直接返回HttpResponseMessage。