1

The task is to serialize the class in json and pass it to POST on the server. I wrote the code and it works, but I have a feeling that I have done a lot of unnecessary things. Prompt good practice to solve my problem.

//package - a serializable object that must be passed
JsonPackage package = new JsonPackage( userData ); 
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer( typeof( JsonPackage ) );

WebRequest request = WebRequest.Create( "http://localhost:52733/set" );
request.ContentType = "application/json";
request.Method = "POST";

MemoryStream ms = new MemoryStream();

jsonFormatter.WriteObject( ms, package );

ms.Flush();
ms.Position = 0;

StreamReader sr = new StreamReader( ms );
string jsonString = sr.ReadToEnd();

StreamWriter sw = new StreamWriter( request.GetRequestStream() );
sw.Write( jsonString );

sr.Dispose();
sw.Dispose();
ms.Dispose();
request.GetResponse();

UPDATE Thanks to all for the answers, you helped me to learn a lot. I took another advice and wrote as follows:

//package - a serializable object that must be passed
JsonPackage package = new JsonPackage( Data );
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer( typeof( JsonPackage ) );

WebRequest request = WebRequest.Create( "http://localhost:52733/set" );
request.ContentType = "application/json";
request.Method = "POST";

using ( var stream = request.GetRequestStream() )
{
    jsonFormatter.WriteObject( stream, package );
}
request.GetResponse();

Tell me there are flaws in my decision?

Vas Mil
  • 605
  • 1
  • 8
  • 21

3 Answers3

1

If you use NewtonSoft.Json, the serialization step will be a simple JsonConvert.SerializeObject(<<object>>). Hope this helps.\

Below is the simplified version of your code.

            var client = new System.Net.Http.HttpClient();

            var content = new     StringContent(JsonConvert.SerializeObject(data));
            client.BaseAddress = new Uri("http://localhost:52733/");
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var response = client.PostAsync("set", content).Result;
            //do what ever you want to do with response
CodeNinja
  • 94
  • 1
  • 6
  • Thank you for your help. But I do not use NewtonSoft. I do not want to drag extra library. – Vas Mil Feb 16 '18 at 06:51
  • use this [link](https://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4) if you don't want to use `NewtonSoft.Json`. . But I believe Microsoft themselves suggest using `JSON.Net`. – CodeNinja Feb 16 '18 at 06:58
1

You could indeed reduce the number of lines using HttpClient and its PostAsJsonAsync method. Since the method is asynchronous and I assume the method where your code is may not be you will need to access the PostAsJsonAsync's awaiter to grab the result of the request.

var client = new HttpClient();

// response is an HttpResponseMessage instance
var response = client.PostAsJsonAsync("http://localhost:52733/set", userData)
                     .GetAwaiter().GetResult();

You can also get more details about HttpClient usages there: https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

CodingNagger
  • 1,178
  • 1
  • 11
  • 26
  • My HttpClient does not contain PostAsJsonAsync, what's wrong? Maybe it's because I'm using .net core? – Vas Mil Feb 16 '18 at 09:03
  • It seems that in .net core it is an extension method, you can find more details there: https://stackoverflow.com/questions/40027299/where-is-postasjsonasync-method-in-asp-net-core – CodingNagger Feb 16 '18 at 09:14
0

I hope I can help. I use restSharp. To use it, you need to install RestSharp

http://restsharp.org/ https://www.nuget.org/packages/RestSharp/106.3.0-alpha0002

and NewtonSoft.Json .

https://www.nuget.org/packages/newtonsoft.json/

private bool Post(<<DataStaructure>> inputParam)
    {
        var jsonSerializerSettings =
            new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };

        var client = new RestClient("http://localhost:52733/set/");
        var request = new RestRequest(Method.POST);
        var jsonToSend = JsonConvert.SerializeObject(inputParam, jsonSerializerSettings);
        request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);

        if (response.IsSuccessful == false)
        {
            throw new Exception(response.ErrorMessage);
        }
        else
        {
            return Convert.ToBoolean(response.Content);

        }
    }
BehrouzMoslem
  • 9,053
  • 3
  • 27
  • 34