首页 > 解决方案 > Azure Functions 从调用端点获取参数

问题描述

我正在尝试实现一种方法,该方法返回任何调用的 Azure 函数的参数名称

如果我有这个 Azure 功能代码:

[FunctionName("Something")]
 public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "customer/{param1}/{param2}")]HttpRequestMessage req, string param1, string param2, TraceWriter log)
 {

     //get the route params by calling the helper function
     //my body
 }

我可能的方法:

  1. 我正在尝试使用StackTrace并搜索“运行”功能,但我无法进入参数名称。
  2. 使用HttpRequestMessage:我可以找到 url 但里面有值,但是我需要参数的实际名称

标签: c#azureazure-functions

解决方案


路由属性(连同其他触发器信息)内置于function.json. 文件结构如下。

{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.21",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "httpTrigger",
      "route": "customer/{param1}/{param2}",
      "methods": [
        "get",
        "post"
      ],
      "authLevel": "function",
      "name": "req"
    }
  ],
  "disabled": false,
  "scriptFile": "../bin/FunctionAppName.dll",
  "entryPoint": "FunctionAppName.FunctionName.Run"
}

所以一种棘手的方法是阅读function.json

添加ExecutionContext context到方法签名中,以便我们可以直接获取函数目录。

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "customer/{param1}/{param2}")]HttpRequestMessage req, string param1, string param2, TraceWriter log, ExecutionContext context)
 {

     //get the route params by calling the helper function
     GetRouteParams(context, log);
     //my body
 }

    public static void GetRouteParams(ExecutionContext context, TraceWriter log)
    {
        //function.json is under function directory
        using (StreamReader r = File.OpenText(context.FunctionDirectory + "/function.json"))
        {
            // Deserialize json
            dynamic jObject = JsonConvert.DeserializeObject(r.ReadToEnd());
            string route = jObject.bindings[0].route.ToString();

            // Search params name included in brackets
            Regex regex = new Regex(@"(?<=\{)[^}]*(?=\})", RegexOptions.IgnoreCase);
            MatchCollection matches = regex.Matches(route);

            var list = matches.Cast<Match>().Select(m => m.Value).Distinct().ToList();
            log.Info("[" + string.Join(", ", list) + "]");
        }
    }

推荐阅读