Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Definition for GetQueryNameValuePairs in Azure Function

All, I'm working on my first Azure Function. The intent of the function is to take in text and spell check it using the Bing cognitive API. However, I am unable to compile because at the string text = req.GetQueryNameValuePairs()... line in my code because it states HTTPRequestMessage does not contain a definition for 'GetQueryNameValuePairs' and no extension method 'GetQueryNameValuePairs' accepting a first argument of type 'HttpRequestMessage' could be found (are you missing a using directive or an assembly reference?).

Any help would be appreciated.

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);    
        }
    }
}
like image 434
jgoraya Avatar asked Nov 14 '18 04:11

jgoraya


2 Answers

Looks like you have created an Azure Function v2(.Net Core). There's no such method GetQueryNameValuePairs on HttpRequestMessage in .Net Core/Standard assembly, it's available in .Net Framework.

The quick fix would be create a v1(.NetFramework) Function Project. If you want to stay with v2 function, code refactor is necessary.

In a v2 Httptrigger template, you can see HttpRequest req(in your grey comment) and it uses req.Query["name"] to get query parameter. There're several other changes necessary as we changed HttpRequestMessage to HttpRequest. Besides, TraceWriter in v1 is also abandoned, in v2 we use ILogger.

like image 176
Jerry Liu Avatar answered Sep 22 '22 21:09

Jerry Liu


Assuming you have query parameters: firstname and lastname, then you could try this:

    var qs = req.RequestUri.ParseQueryString();

    string firstName = qs.Get("firstname");
    string lastName = qs.Get("lastname");
like image 40
Jay Avatar answered Sep 20 '22 21:09

Jay