c# - 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
}
- 如果我使用以下方法调用函数端点: http://localhost:80/customer/1/2
- 辅助函数的输出 -> ['param1', 'param2']
我可能的方法:
- 我正在尝试使用
StackTrace
并搜索“运行”功能,但我无法进入参数名称。 - 使用
HttpRequestMessage
:我可以找到 url 但里面有值,但是我需要参数的实际名称
解决方案
路由属性(连同其他触发器信息)内置于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) + "]");
}
}
推荐阅读
- linux - 放大稀疏文件
- coq - 如何应用特定命令
- javascript - TypeError:无法读取未定义的属性“varName”
- express-session - 使用快速会话未收到任何 cookie 作为响应
- azerothcore - 使用 master 分支的最新更新更新 Azerothcore
- node.js - 从 AWS S3 ORC 格式数据库中读取节点中的数据
- eclipse - Eclipse 中的 Perl EPIC:尝试运行 Perl 脚本时如何摆脱这个 Ant Build 对话框?
- php - 我想在 php 中创建一个简单的日志文件,该文件存储有关软件中发生的一切的所有信息?
- reactjs - React Create App 中的 npm build 和 babel 问题
- python - _tkinter.TclError:无法连接以在绘图中显示“:0”