Azure函数从调用终结点获取参数

时间:2018-09-17 21:17:53

标签: c# azure 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,但其中包含值,但是我需要参数的实际名称

1 个答案:

答案 0 :(得分:1)

路由属性(以及其他触发信息)已内置到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) + "]");
        }
    }