Search code examples
c#jsonposthttpwebrequestwebrequest

C# API Call doesn't work with HttpWebRequest but do work with Postman


I've the following postman request: enter image description here enter image description here

Which returns me as expected an URL: enter image description here

I'm trying to mimic this operation with a .Net Core 2.0 application, with the following code:

static void Main(string[] args)
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://epaper.20minuten.ch/index.cfm/epaper/1.0/getEditionDoc");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";

    var serializer = new Newtonsoft.Json.JsonSerializer();
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
        {
            serializer.Serialize(tw,
                new
                {
                    editions = new[]
                    {
                            new
                            {
                                defId = "648",
                                publicationDate = "2018-03-06"
                            }
                    },
                    isAttachment = true,
                    fileName = "Gesamtausgabe_Lausanne_2018-03-06.pdf"
                });
        }
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        Console.ReadLine();
    }
}

But I receive 500 errors. What did I miss?


Solution

  • Postman can generate a wide variety of code. To use RestSharp with C# click the code button/link and choose C# (RestSharp) from the dropdown.

    It should resemble:

    enter image description here

    Someday I will contribute a generator for HttpClient and HttpWebRequest