在孤立的 Azure Functions 中访问 URL 中的属性的正确方法是什么

What is the proper way to access properties in a URL in isolated Azure Functions

我一直在寻找是否有不同的方法来访问在独立的 Azure 函数 (.NET 5) 中传递的参数

这是我的路线: Route = "v1/session/find/{ipAddress}/{sessionId}"

更多信息完整方法签名: public HttpResponseData 运行([HttpTrigger(AuthorizationLevel.Function,"get", Route = "v1/session/find/{ipAddress}/{sessionId}")] HttpRequestData 请求, FunctionContext executionContext)

以下是我如何访问这些参数并清理它们:

        var ipAddress = req.Url.Segments[5];
        ipAddress = ipAddress.TrimEnd(new[] { '/' });
        ipAddress = HttpUtility.UrlDecode(ipAddress).Trim();
        var sessionId = req.Url.Segments[6];
        sessionId = sessionId.TrimEnd(new[] {'/'});
        sessionId = HttpUtility.UrlDecode(sessionId).Trim();

我遗漏了什么,或者这是目前获取这些路由参数的唯一方法吗?

.Net 5

@fgalarraga88,你是对的。我没有看到您特别声明了 .Net 5。这是适用于 .Net 5 Isolated 的代码。我在 VS 2019 16.10 中本地测试了这个并且它有效。

只需使用属性设置路由(在大括号中为您的模式提供参数),然后将预期的路由参数作为参数添加到方法中。就这么简单。

public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/session/find/{ipAddress}/{sessionId}")] 
   HttpRequestData req, 
   string ipAddress, 
   string sessionId,
   FunctionContext executionContext)
   {
      var response = req.CreateResponse(HttpStatusCode.OK);
      response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

      response.WriteString($"IP Addresss: {ipAddress} and Session Id: {sessionId}");

      return response;
   }

如果对其他人有用,请留下我的原始答案以供参考。

.网络核心 3.1

查看 HttpTrigger (https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=csharp#customize-the-http-endpoint) 的文档,其中概述了如何处理路由变量。

根据这些文档,自定义路由 属性:

{
    "bindings": [
    {
        "type": "httpTrigger",
        "name": "req",
        "direction": "in",
        "methods": [ "get" ],
        "route": "products/{category:alpha}/{id:int?}"
    },
    {
        "type": "http",
        "name": "res",
        "direction": "out"
    }
    ]
}

将为您的 C# 函数生成以下方法签名:

public static IActionResult Run(HttpRequest req, string category, int? id, ILogger log)
{
    var message = String.Format($"Category: {category}, ID: {id}");
    return (ActionResult)new OkObjectResult(message);
}

并且您无需任何自定义细分解析即可访问“类别”和“id”。只需将此示例与您的路线一起使用并替换 ipAddress 和 sessionId 变量。