Click here to Skip to main content
15,886,008 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
This below code is working fine, i just wanted to do it using webclient without async.

Or can we remove anyways asnc from below method and make it like regular method.

// Calling method from program.cs using console application

static void Main(string[] args)
      {
          AsyncCallbackUrlPost("f0c9b87f41fd0b7824ffdadeccefefefdd3c39929dbceca61b3450d497981a5eeeec354713d61263a71e3a953beebf62b12d6d9819ebb0593e7947766e8bef03", "http://localhost:54262/api/Payload");

          Console.ReadLine();
      }



// This method i want to replace with webclient

public static async Task AsyncCallbackUrlPost(string loanBeamMessageHash, string callbackURL)
        {
            HttpResponseMessage httpResponseMessage = null;
            try
            {
                Uri objUri = new Uri(callbackURL);
                //Create an Http client and set the headers we want 
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //Add it to Response Header and call it "LoanBeam_MessageHash"
                httpClient.DefaultRequestHeaders.Add("LoanBeam_MessageHash", loanBeamMessageHash);
                httpClient.DefaultRequestHeaders.Host = objUri.Host;
                StringContent theContent = new StringContent(loanBeamMessageHash, System.Text.Encoding.UTF8, "application/json");
                //Post the data 
                httpResponseMessage = await httpClient.PostAsync(objUri, theContent);
                //handle status code 200
                if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                {

                    Console.WriteLine("HTTP status success: " + httpResponseMessage.ReasonPhrase);
                    return;
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("HTTP status error: " + httpResponseMessage.ReasonPhrase);
            }

        }


What I have tried:

My above code is working fine, i just wanted to do it using webclient without async. 
Posted
Updated 7-Feb-18 2:47am
Comments
Sinisa Hajnal 7-Feb-18 8:33am    
why?
Richard Deeming 8-Feb-18 12:13pm    
If you're just worried about the program being terminated before the async call completes, then wait for the async call to complete:
AsyncCallbackUrlPost("...", "...").GetAwaiter().GetResult();

Or, if you target C# 7.1, you can make the Main method async:
http://pmichaels.net/2017/09/10/async-main-c-7-1/[^]
Adityakumar2318 15-Feb-18 12:36pm    
Thanks Richard for providing beautiful tips. Can you please let me know the recent doubts?
Adityakumar2318 15-Feb-18 12:35pm    
I am able to return HttpStatusCode using HttpClient? Can i get HttpStatusCode like 200(OK) by using WebClient too?
Richard Deeming 15-Feb-18 12:43pm    
httpResponseMessage.StatusCode
You've already got that in your code.

Using the low-level WebRequest / WebResponse classes, if you cast the response to the HttpWebResponse type, it has a StatusCode property. However, it tends to throw an exception for anything other than a success status code.

For the WebClient class, the status code might be contained in the ResponseHeaders collection. But again, it tends to throw an exception for anything other than a success status code.

1 solution

There is an example on the WebClient documentation.

WebClient Class (System.Net)[^]
 
Share this answer
 
Comments
Adityakumar2318 8-Feb-18 5:53am    
Yes, but it is not showing how to pass the value using header.
F-ES Sitecore 8-Feb-18 5:58am    
The sample does show how to add headers.
Adityakumar2318 11-Feb-18 14:35pm    
Thanks. But sample does not show how to send json value using body.
F-ES Sitecore 12-Feb-18 4:36am    
JSON is just text, there's nothing special about it. Google "post data webclient" and you'll find an example that sends data in the body so use that to send your json.
Adityakumar2318 15-Feb-18 12:28pm    
Thanks. My issue is fixed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900