Kar*_*hik 3 c# azure azure-functions
在 Visual Studio 2017(HTTPTrigger基于)中创建了一个新的 Azure 函数,并且在使用自定义路由传递参数时遇到了困难。下面是代码摘录:
[FunctionName("RunTest")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "orchestrators/contoso_function01/{id:int}/{username:alpha}")] HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// parse query parameter
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0)
.Value;
string instanceId = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "username", true) == 0)
.Value;
if (name == null)
{
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
name = data?.name;
}
return name == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下 URL 访问函数,但无法使用API从查询字符串中检索ID或UserName值GetQueryNameValuePairs(),因为它在集合中只有 0 个项目:
http://localhost:7071/api/orchestrators/contoso_function01/123/abc
http://localhost:7071/api/orchestrators/contoso_function01/?id=123&username=abc
Run Code Online (Sandbox Code Playgroud)
ihi*_*imv 10
如果您想在 URL 本身中使用参数而不是从HttpRequestMessage req对象中读取参数,可以执行以下操作:
示例网址:
http://localhost:7201/api/orchestrators/contoso_function01/{id}/{username}
Run Code Online (Sandbox Code Playgroud)
支持代码:
[FunctionName("RunTest")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post",
Route = "orchestrators/contoso_function01/{id}/{username}")]
HttpRequestMessage req, int id, string username, TraceWriter log)
{
log.Info($"Id = {id}, Username = {username}");
// more code goes here...
}
Run Code Online (Sandbox Code Playgroud)
这里我们做了两处修改:
添加 id 和用户名作为 URL 的一部分。
Route = "orchestrators/contoso_function01/{id}/{username}"
为 id 和 username 声明两个附加变量。变量的名称必须与 URL 中的参数名称匹配(不区分大小写)。
HttpRequestMessage req, int id, string username, TraceWriter log
旁注HttpRequestMessage req:即使代码中未使用,也不要从函数参数中删除。删除相同的内容将停止参数的绑定(不确定这是有意的还是错误)。
此解决方案已在 Azure Functions 版本 3 上进行了测试。
进一步阅读:使用 Azure Functions 的无服务器 C#:HTTP 触发函数。
不确定这是否是处理使用 Azure 函数为 HTTP 请求传递参数的这种需要的正确方法,但是如果我为每个查询字符串包含具有匹配参数名称的参数(这显然是使绑定工作所必需的),它会自动分配给 URL 中传递给相应参数的值。
[FunctionName("HttpRunSingle")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "orchestrators/contoso_function01/{id:int}/{username:alpha}")]
HttpRequestMessage req,
int id,
string username,
TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
return (id == 0 || string.IsNullOrEmpty(username))
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Hello " + id + " " + username);
}
Run Code Online (Sandbox Code Playgroud)