Search code examples
c#dotnet-httpclient

The server is returning that the request is bad, but my simple post looks correct


I've got a fairly simple straightforward post I am trying to send to the server that controls a printer. Ultimately it's for a asp.net web application, but figured I should dumb it down first.

Using the Postman app I can submit the job to the printer with the following:

Post: 127.0.0.1:8083/rxlabelprint

Body:
{   
     "name": "Natalie D Sanderson",
    "dob": "08/05/2009",                            
    "directions": "Take twice daily",     
    "med-details": "Amox 500mg",              
    "dry-run": "True"                               
}

This works great!

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            string content = "{'name': 'Natalie D Sanderson', 'dob': '08/05/2009', 'directions': 'Take twice daily', 'med-details': 'Amox 500mg','dry-run': 'True'}";
            var result = client.PostAsync(
                "http://localhost:8083/rxlabelprint",
         new StringContent(content, Encoding.UTF8, "application/json"));
            string resultContent = result.Result.ToString();  // Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
            Console.ReadLine();
        }
    }

Error Message:

StatusCode: 400, ReasonPhrase: 'BAD REQUEST', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Connection: keep-alive Date: Wed, 31 Jul 2019 21:31:17 GMT Server: nginx/1.15.8 Content-Length: 92 Content-Type: application/json }


Solution

  • I needed to Post, but otherwise the comment was great! Here is my final answer:

        var targeturi = "http://localhost:8083/rxlabelprint";
        var client = new System.Net.Http.HttpClient();
    
        HttpContent content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("name", "Natalie Sanderson"),
            new KeyValuePair<string, string>("dob", "08/05/2005"),
            new KeyValuePair<string, string>("directions", "Take twice daily"),
            new KeyValuePair<string, string>("med-details", "Amox 500mg"),
            new KeyValuePair<string, string>("dry-run", "False")
        });
    
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");  
        var result = client.PostAsync(targeturi, content).Result;
        string resultContent = await result.Content.ReadAsStringAsync();
        //log response
        Console.WriteLine(resultContent);
        Console.ReadLine();