如何在 Azure 函数的自定义 HTTP 路由中指定查询参数?

Kzr*_*tof 8 c# azure azure-functions

我有一个 Azure 函数,我想设置一个自定义 HTTP 端点。在回答这个 SO question 之后,我得到了这样的结果:

[FunctionName("DoSomething")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/tenants/{tenantId}/locations/{locationId}/products?manufacturer={manufacturer}")]
                HttpRequest request, ILogger logger, string tenantId, string locationId, string manufacturer)
{
        // 
}
Run Code Online (Sandbox Code Playgroud)

但是,Webjob 不接受该路由:

"v1/tenants/{tenantId}/locations/{locationId}/products?manufacturer={manufacturer}"
Run Code Online (Sandbox Code Playgroud)

原因是因为问号“?”:

创建名称为“DoSomething”且模板为“api/v1/tenants/{tenantId}/locations/{locationId}/products?manufacturer={manufacturer}”的路由时出错。文字部分 'products?manufacturer=' 无效。文字部分不能包含“?” 特点。参数名称:routeTemplate 文字部分 'products?manufacturer=' 无效。文字部分不能包含“?” 特点。

如何在 Azure 函数的自定义 HTTP 终结点中指定查询参数?

Jer*_*Liu 5

恐怕无法在 Route 中放置查询参数。

Microsoft.AspNetCore.Routing:文字部分“products?manufacturer=”无效。文字部分不能包含“?” 特点。

它是 ASP.NET Routing 的内置限制,Azure Function 使用它来为 Http 触发器构建路由。

允许我将值作为 Run 的方法参数之一而不是戳 HttpRequest 实例

如果这就是你想在路由中放置查询参数的原因,我建议你添加IDictionary<string, string> query方法签名并用于query["manufacturer"]访问函数代码中的参数。但老实说,它几乎与request.Query["manufacturer"].

或者您可能必须遵循建议,将查询参数转换为 route like products/{productId}