{"id":251,"date":"2021-04-01T20:33:23","date_gmt":"2021-04-01T11:33:23","guid":{"rendered":"https:\/\/mvc.auctionpro.co.kr\/?page_id=251"},"modified":"2021-04-01T20:33:29","modified_gmt":"2021-04-01T11:33:29","slug":"systemnethttpjsonsamples","status":"publish","type":"page","link":"https:\/\/mvc.auctionpro.co.kr\/?page_id=251","title":{"rendered":"SystemNetHttpJsonSamples"},"content":{"rendered":"<h3> Remark : <\/h3>\n<h4>  Console with Http and  Json <\/h4>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/mvc.auctionpro.co.kr\/wp-content\/uploads\/2021\/04\/SystemNetHttpJsonSamples.jpg\" alt=\"\" width=\"466\" height=\"294\" class=\"alignnone size-full wp-image-252\" srcset=\"https:\/\/mvc.auctionpro.co.kr\/wp-content\/uploads\/2021\/04\/SystemNetHttpJsonSamples.jpg 466w, https:\/\/mvc.auctionpro.co.kr\/wp-content\/uploads\/2021\/04\/SystemNetHttpJsonSamples-300x189.jpg 300w\" sizes=\"auto, (max-width: 466px) 100vw, 466px\" \/><\/p>\n<pre class=\"lang:default decode:true \" title=\"Program.cs\" >using Newtonsoft.Json;\r\nusing System;\r\nusing System.IO;\r\nusing System.Net.Http;\r\nusing System.Net.Http.Json;\r\nusing System.Threading.Tasks;\r\nusing System.Collections.Generic;\r\n\r\nnamespace SystemNetHttpJsonSamples\r\n{\r\n    partial class Program\r\n    {   \r\n        static async Task Main()\r\n        {\r\n            const string validUserUri = \"https:\/\/example.com\/users\/1\";\r\n            const string postUserUri = \"https:\/\/example.com\/users\";\r\n\r\n            var httpClient = new HttpClient(new FakeEndpointHandler());\r\n\r\n            User user = null;\r\n\r\n            user = await InefficientStringApproach(validUserUri, httpClient);\r\n\r\n            user = await StreamWithNewtonsoftJson(validUserUri, httpClient);\r\n\r\n            user = await WebApiClient(validUserUri, httpClient);\r\n\r\n            user = await StreamWithSystemTextJson(validUserUri, httpClient);\r\n\r\n            user = await GetJsonHttpClient(validUserUri, httpClient);\r\n\r\n            user = await GetJsonFromContent(validUserUri, httpClient);\r\n\r\n            await PostJsonHttpClient(postUserUri, httpClient);\r\n\r\n            await PostJsonContent(postUserUri, httpClient);\r\n\r\n            _ = Console.ReadLine();\r\n        }\r\n\r\n        private static async Task&lt;User&gt; InefficientStringApproach(string uri, HttpClient httpClient)\r\n        {\r\n            var httpResponse = await httpClient.GetAsync(uri);\r\n\r\n            if (httpResponse.Content is object &amp;&amp; httpResponse.Content.Headers.ContentType.MediaType == \"application\/json\")\r\n            {\r\n                var jsonString = await httpResponse.Content.ReadAsStringAsync();\r\n\r\n                \/\/Console.WriteLine(\"OK\");\r\n\r\n                return JsonConvert.DeserializeObject&lt;User&gt;(jsonString);\r\n            }\r\n            else\r\n            {\r\n                Console.WriteLine(\"HTTP Response was invalid and cannot be deserialised.\");\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private static async Task&lt;User&gt; StreamWithNewtonsoftJson(string uri, HttpClient httpClient)\r\n        {\r\n            using var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);\r\n\r\n            httpResponse.EnsureSuccessStatusCode(); \/\/ throws if not 200-299\r\n\r\n            if (httpResponse.Content is object &amp;&amp; httpResponse.Content.Headers.ContentType.MediaType == \"application\/json\")\r\n            {\r\n                var contentStream = await httpResponse.Content.ReadAsStreamAsync();\r\n\r\n                using var streamReader = new StreamReader(contentStream);\r\n                using var jsonReader = new JsonTextReader(streamReader);\r\n\r\n                JsonSerializer serializer = new JsonSerializer();\r\n\r\n                try\r\n                {\r\n                    return serializer.Deserialize&lt;User&gt;(jsonReader);\r\n                }\r\n                catch(JsonReaderException)\r\n                {\r\n                    Console.WriteLine(\"Invalid JSON.\");\r\n                } \r\n            }\r\n            else\r\n            {\r\n                Console.WriteLine(\"HTTP Response was invalid and cannot be deserialised.\");\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private static async Task&lt;User&gt; WebApiClient(string uri, HttpClient httpClient)\r\n        {\r\n            using var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);\r\n\r\n            httpResponse.EnsureSuccessStatusCode(); \/\/ throws if not 200-299\r\n\r\n            try\r\n            {\r\n                return await httpResponse.Content.ReadAsAsync&lt;User&gt;();\r\n            }\r\n            catch \/\/ Could be ArgumentNullException or UnsupportedMediaTypeException\r\n            {\r\n                Console.WriteLine(\"HTTP Response was invalid or could not be deserialised.\");\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private static async Task&lt;User&gt; StreamWithSystemTextJson(string uri, HttpClient httpClient)\r\n        {\r\n            using var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);\r\n\r\n            httpResponse.EnsureSuccessStatusCode(); \/\/ throws if not 200-299\r\n\r\n            if (httpResponse.Content is object &amp;&amp; httpResponse.Content.Headers.ContentType.MediaType == \"application\/json\")\r\n            {\r\n                var contentStream = await httpResponse.Content.ReadAsStreamAsync();\r\n\r\n                try\r\n                {\r\n                    return await System.Text.Json.JsonSerializer.DeserializeAsync&lt;User&gt;(contentStream, new System.Text.Json.JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true });\r\n                }\r\n                catch (JsonException) \/\/ Invalid JSON\r\n                {\r\n                    Console.WriteLine(\"Invalid JSON.\");\r\n                }                \r\n            }\r\n            else\r\n            {\r\n                Console.WriteLine(\"HTTP Response was invalid and cannot be deserialised.\");\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private static async Task&lt;User&gt; GetJsonHttpClient(string uri, HttpClient httpClient)\r\n        {\r\n            try\r\n            {\r\n                var user = await httpClient.GetFromJsonAsync&lt;User&gt;(uri);\r\n\r\n                return user;\r\n            }\r\n            catch (HttpRequestException) \/\/ Non success\r\n            {\r\n                Console.WriteLine(\"An error occurred.\");\r\n            }\r\n            catch (NotSupportedException) \/\/ When content type is not valid\r\n            {\r\n                Console.WriteLine(\"The content type is not supported.\");\r\n            }\r\n            catch (JsonException) \/\/ Invalid JSON\r\n            {\r\n                Console.WriteLine(\"Invalid JSON.\");\r\n            }\r\n            \r\n            return null;\r\n        }\r\n\r\n        private static async Task&lt;User&gt; GetJsonFromContent(string uri, HttpClient httpClient)\r\n        {\r\n            var request = new HttpRequestMessage(HttpMethod.Get, uri);\r\n            request.Headers.TryAddWithoutValidation(\"some-header\", \"some-value\");\r\n\r\n            using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);\r\n\r\n            if (response.IsSuccessStatusCode)\r\n            {\r\n                \/\/ perhaps check some headers before deserialising\r\n                \r\n                try\r\n                {\r\n                    return await response.Content.ReadFromJsonAsync&lt;User&gt;();\r\n                }\r\n                catch (NotSupportedException) \/\/ When content type is not valid\r\n                {\r\n                    Console.WriteLine(\"The content type is not supported.\");\r\n                }\r\n                catch (JsonException) \/\/ Invalid JSON\r\n                {\r\n                    Console.WriteLine(\"Invalid JSON.\");\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private static async Task PostJsonHttpClient(string uri, HttpClient httpClient)\r\n        {\r\n            var postUser = new User { Name = \"Steve Gordon\" };\r\n\r\n            var postResponse = await httpClient.PostAsJsonAsync(uri, postUser);\r\n\r\n            postResponse.EnsureSuccessStatusCode();\r\n        }\r\n\r\n        private static async Task PostJsonContent(string uri, HttpClient httpClient)\r\n        {\r\n            var postUser = new User { Name = \"Steve Gordon\" };\r\n\r\n            var postRequest = new HttpRequestMessage(HttpMethod.Post, uri)\r\n            {\r\n                Content = JsonContent.Create(postUser)\r\n            };\r\n\r\n            var postResponse = await httpClient.SendAsync(postRequest);\r\n\r\n            postResponse.EnsureSuccessStatusCode();\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<pre class=\"lang:default decode:true \" title=\"Address.cs\" >namespace SystemNetHttpJsonSamples\r\n{\r\n    public class Address\r\n    {\r\n        public string Street { get; set; }\r\n        public string City { get; set; }\r\n        public string Postcode { get; set; }\r\n        public Geo Geo { get; set; }\r\n    }\r\n}\r\n<\/pre>\n<pre class=\"lang:default decode:true \" title=\"Company.cs\" >namespace SystemNetHttpJsonSamples\r\n{\r\n    public class Company\r\n    {\r\n        public string Name { get; set; }\r\n        public string CatchPhrase { get; set; }\r\n    }\r\n}\r\n<\/pre>\n<pre class=\"lang:default decode:true \" title=\"FakeEndpointHandler.cs\" >using System.Net.Http;\r\nusing System.Text;\r\nusing System.Threading;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace SystemNetHttpJsonSamples\r\n{\r\n    partial class Program\r\n    {\r\n        internal class FakeEndpointHandler : DelegatingHandler\r\n        {\r\n            protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n            {\r\n                HttpResponseMessage responseMessage = null;\r\n\r\n                if (request.Method == HttpMethod.Get &amp;&amp; request.RequestUri.AbsolutePath == \"\/users\/1\")\r\n                {\r\n                    responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK)\r\n                    {\r\n                        Content = new StringContent(\"{\\\"id\\\":1,\\\"name\\\":\\\"Steve Gordon\\\",\\\"username\\\":\\\"stevejgordon\\\",\\\"email\\\":\\\"stevejgordon@example.com\\\",\\\"address\\\":{\\\"street\\\":\\\"1 Madeup Place\\\",\\\"city\\\":\\\"Sometown\\\",\\\"postcode\\\":\\\"AA1 1AA\\\",\\\"geo\\\":{\\\"lat\\\":\\\"0.0000\\\",\\\"lng\\\":\\\"0.0000\\\"}},\\\"phone\\\":\\\"00000 000000\\\",\\\"website\\\":\\\"stevejgordon.co.uk\\\",\\\"company\\\":{\\\"name\\\":\\\"An Impressive Name\\\",\\\"catchPhrase\\\":\\\"Building .NET Code everyday!\\\"}}\", Encoding.UTF8, \"application\/json\")\r\n                    };\r\n                }\r\n\r\n                if (request.Method == HttpMethod.Get &amp;&amp; request.RequestUri.AbsolutePath == \"\/users\/2\")\r\n                {\r\n                    responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);\r\n                }\r\n\r\n                if (request.Method == HttpMethod.Post &amp;&amp; request.RequestUri.AbsolutePath == \"\/users\")\r\n                {\r\n                    responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.Created);\r\n                }\r\n\r\n                return Task.FromResult(responseMessage);\r\n            }\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<pre class=\"lang:default decode:true \" title=\"User.cs\" >namespace SystemNetHttpJsonSamples\r\n{\r\n    public class User\r\n    {\r\n        public int Id { get; set; }\r\n        public string Name { get; set; }\r\n        public string Username { get; set; }\r\n        public string Email { get; set; }\r\n        public Address Address { get; set; }\r\n        public string Phone { get; set; }\r\n        public string Website { get; set; }\r\n        public Company Company { get; set; }\r\n    }\r\n}\r\n<\/pre>\n<pre class=\"lang:default decode:true \" title=\"Geo.cs\" >namespace SystemNetHttpJsonSamples\r\n{\r\n    public class Geo\r\n    {\r\n        public string Lat { get; set; }\r\n        public string Lng { get; set; }\r\n    }\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Remark : Console with Http and Json using Newtonsoft.Json; using System; using System.IO; using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; using System.Collections.Generic; namespace SystemNetHttpJsonSamples { partial class Program { static async Task Main() { const string validUserUri = &#8220;https:\/\/example.com\/users\/1&#8221;; const string postUserUri = &#8220;https:\/\/example.com\/users&#8221;; var httpClient = new HttpClient(new FakeEndpointHandler()); User user = null; user =\u2026 <span class=\"read-more\"><a href=\"https:\/\/mvc.auctionpro.co.kr\/?page_id=251\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-251","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/mvc.auctionpro.co.kr\/index.php?rest_route=\/wp\/v2\/pages\/251","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mvc.auctionpro.co.kr\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/mvc.auctionpro.co.kr\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/mvc.auctionpro.co.kr\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mvc.auctionpro.co.kr\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=251"}],"version-history":[{"count":1,"href":"https:\/\/mvc.auctionpro.co.kr\/index.php?rest_route=\/wp\/v2\/pages\/251\/revisions"}],"predecessor-version":[{"id":253,"href":"https:\/\/mvc.auctionpro.co.kr\/index.php?rest_route=\/wp\/v2\/pages\/251\/revisions\/253"}],"wp:attachment":[{"href":"https:\/\/mvc.auctionpro.co.kr\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=251"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}