Sagotharan
Sagotharan

Reputation: 2626

Get json string in C#

I have created a post method for sending json like below.,

daywiseInventory Page C# -

public string daywiseInventory(string JsonQuery)
{
    try
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("www.example.com/booking.aspx");
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = JsonQuery;

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();
            return responseText;
        }
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

And I want to get the posting json in Booking Page_Load. How can i code for this?

when i trying the below code in page_load was not helping. it through Invalid URI: The URI is empty Error.

HttpWebRequest webRequest = WebRequest.Create ("") as HttpWebRequest;
HttpWebResponse response = webRequest.GetResponse () as HttpWebResponse;

// Read the response
StreamReader reader = new StreamReader (response.GetResponseStream ());
var responseText = reader.ReadToEnd ();

I am new to this json. So kindly explain how to get the json string that i have post?

Upvotes: 3

Views: 381

Answers (1)

Dominic Zukiewicz
Dominic Zukiewicz

Reputation: 8444

Looking at your code:

HttpWebRequest webRequest = WebRequest.Create ("") as HttpWebRequest;

You haven't specified the Uri in the WebRequest.Create(""), so to correct it, add a URI to connect to.

HttpWebRequest webRequest = WebRequest.Create ("http://my.website.to/connect.to.aspx") as HttpWebRequest;

Upvotes: 1

Related Questions