将URL中的参数作为查询字符串传递给Azure函数(HttpTrigger)

时间:2019-02-12 19:39:17

标签: 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);
        }

试图使用以下URL访问该函数,但由于使用了GetQueryNameValuePairs()API,因此无法从查询字符串中检索ID或UserName值,因为该集合中只有0个项目:

http://localhost:7071/api/orchestrators/contoso_function01/123/abc http://localhost:7071/api/orchestrators/contoso_function01/?id=123&username=abc

4 个答案:

答案 0 :(得分:4)

不确定这是否是处理通过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);
        }

答案 1 :(得分:1)

您可以这样做:

var query = System.Web.HttpUtility.ParseQueryString(req.RequestUri.Query);
string userid = query.Get("username");

答案 2 :(得分:1)

对于任何想像这样使用 URL 的人:

http://localhost:7201/api/orchestrators/contoso_function01/<123>/<abc>

其中 123 是整数 idabc 是我们希望成为 URL 一部分的字符串 username

您可以执行以下操作:

[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...
}

这里我们做了两个改动:

  1. 添加 ID 和用户名作为 URL 的一部分。

    Route = "orchestrators/contoso_function01/{id}/{username}"

  2. 为 id 和 username 声明两个额外的变量

    HttpRequestMessage req, int id, string username, TraceWriter log

此解决方案已在 Azure Functions 版本 3 上进行了测试。

进一步阅读Serverless C# with Azure Functions: HTTP-Triggered Functions

答案 3 :(得分:0)

我尝试了各种各样的东西。这是唯一对我有用的东西。可以与这样的网址配合使用。 https://www.bing.com?id=12345678955&test=12345

string RawUrl = url;
        int index = RawUrl.IndexOf("?");
        if (index > 0)
            RawUrl = RawUrl.Substring(index).Remove(0, 1);

        var query = System.Web.HttpUtility.ParseQueryString(RawUrl);
        userId = query.Get("id");

在使用语句使System.Web.HttpUtility.ParseQueryString正常工作之前,请确保并添加此代码。

#r "System.Web"
相关问题