Azure函数中对GetQueryNameValuePairs的未定义

jgo*_*aya 4 c# azure azure-functions

所有,我正在开发我的第一个Azure功能。该功能的目的是使用Bing认知API接收文本并对其进行拼写检查。但是,我无法编译,因为代码中的字符串text = req.GetQueryNameValuePairs()...行,因为它指出HTTPRequestMessage不包含“ GetQueryNameValuePairs”的定义,并且没有扩展方法“ GetQueryNameValuePairs”接受第一个参数可以找到类型“ HttpRequestMessage”(您是否缺少using指令或程序集引用?)。

任何帮助,将不胜感激。

using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using System.Net;
using System;
using System.Net.Http;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace SpellCheck.Functions
{
    public static class SpellCheck
    {
        [FunctionName("SpellCheck")]
        //public async static Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            //List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>();
            //values.Add(new KeyValuePair<string, string>("text", text));

            //error here
            string text = req.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "text", true) == 0)
                .Value;

            dynamic data = await req.Content.ReadAsAsync<object>();
            text = text ?? data?.text;

            // Replace the accessKey string value with your valid access key. - https://www.codeproject.com/Articles/1221350/Getting-Started-with-the-Bing-Search-APIs
            const string accessKey = "MY_ACCESS_KEY_GOES_HERE";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", accessKey);

            //  The endpoint URI.
            const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/spellcheck?";
            const string uriMktAndMode = "mkt=en-US&mode=proof&";

            HttpResponseMessage response = new HttpResponseMessage();
            string uri = uriBase + uriMktAndMode;

            List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>();
            values.Add(new KeyValuePair<string, string>("text", text));

            using (FormUrlEncodedContent content = new FormUrlEncodedContent(values))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                response = await client.PostAsync(uri, content);
            }

           string client_id;
            if (response.Headers.TryGetValues("X-MSEdge-ClientID", out IEnumerable<string> header_values))
            {
                client_id = header_values.First();
            }

            string contentString = await response.Content.ReadAsStringAsync();

            return text == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass text on the query string or in the request body")
                : req.CreateResponse(HttpStatusCode.OK, "Text to Spell: " + text);    
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*Liu 6

看起来您已经创建了Azure Function v2(.Net Core)。.Net Core / Standard程序GetQueryNameValuePairs集中没有这种方法HttpRequestMessage,.Net Framework中可用。

快速解决方案是创建一个v1(.NetFramework)功能项目。如果要保留v2功能,则必须进行代码重构。

在v2 Httptrigger模板中,您可以看到HttpRequest req(在灰色注释中),它用于req.Query["name"]获取查询参数。当我们更改为时HttpRequestMessage,还需要进行其他一些更改HttpRequest。此外,TraceWriter在v1中也被放弃,在v2中我们使用ILogger


小智 5

假设你有查询参数:firstnamelastname,那么你可以试试这个:

    var qs = req.RequestUri.ParseQueryString();

    string firstName = qs.Get("firstname");
    string lastName = qs.Get("lastname");
Run Code Online (Sandbox Code Playgroud)