Search code examples
c#apihttp-postdotnet-httpclient

Httpclient POST request not working properly


   [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        var data = new { key = key, id = req.Query["mailid"] };
        var result = await myHttpClient.PostAsJsonAsync("https://someapi.com/api/info", data);

        return new OkObjectResult(result);
    }

Hi. Im trying to build an azure function, which gets the variable mailid and sends a POST request to an API with the apikey and the mailID in a body, so it can check the status of the mail and give back if its delivered or not. I dont get it to work and "result" returns a json of the httpClient, with the error code 500. Why doesnt the request work? The API expects the key and id in a JSON format in the POST-body.


Solution

  • [FunctionName("Function1")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                log.LogInformation("C# HTTP trigger function processed a request.");
                string mailid = req.Query["mailid"];
                var data = new Dictionary<string, string> {
                    { "key", key },
                    { "id", mailid },
                };
                //var data = new { key = key, id = req.Query["mailid"] };
                var json = JsonConvert.SerializeObject(data, Formatting.Indented);
                var stringContent = new StringContent(json);
                myHttpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var result = await myHttpClient.PostAsync("https://someapi.com/api/info", stringContent);
                var responseString = await result.Content.ReadAsStringAsync();
    
                return new OkObjectResult(responseString);
            }
    

    I just got it to work without an anonymous type variable, which the senior advised me to use. This gets me the result I wanted. It seems like it didnt get send in the proper post-body, as a proper json.