How to Get The Http Post Data in C#

How to Get the HTTP Post data in C#?

This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.

string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}

Send HTTP POST request in .NET

There are several ways to perform HTTP GET and POST requests:



Method A: HttpClient (Preferred)

Available in: .NET Framework 4.5+, .NET Standard 1.1+, and .NET Core 1.0+.

It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.

using System.Net.Http;

Setup

It is recommended to instantiate one HttpClient for your application's lifetime and share it unless you have a specific reason not to.

private static readonly HttpClient client = new HttpClient();

See HttpClientFactory for a dependency injection solution.



  • POST

      var values = new Dictionary<string, string>
    {
    { "thing1", "hello" },
    { "thing2", "world" }
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();
  • GET

      var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");


Method B: Third-Party Libraries

RestSharp

  • POST

       var client = new RestClient("http://example.com");
    // client.Authenticator = new HttpBasicAuthenticator(username, password);
    var request = new RestRequest("resource/{id}");
    request.AddParameter("thing1", "Hello");
    request.AddParameter("thing2", "world");
    request.AddHeader("header", "value");
    request.AddFile("file", path);
    var response = client.Post(request);
    var content = response.Content; // Raw content as string
    var response2 = client.Post<Person>(request);
    var name = response2.Data.Name;

Flurl.Http

It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.

    using Flurl.Http;


  • POST

      var responseString = await "http://www.example.com/recepticle.aspx"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();
  • GET

      var responseString = await "http://www.example.com/recepticle.aspx"
    .GetStringAsync();


Method C: HttpWebRequest (not recommended for new work)

Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+. In .NET Core, it is mostly for compatibility -- it wraps HttpClient, is less performant, and won't get new features.

using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader


  • POST

      var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

    var postData = "thing1=" + Uri.EscapeDataString("hello");
    postData += "&thing2=" + Uri.EscapeDataString("world");
    var data = Encoding.ASCII.GetBytes(postData);

    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream())
    {
    stream.Write(data, 0, data.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();

    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  • GET

      var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

    var response = (HttpWebResponse)request.GetResponse();

    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


Method D: WebClient (Not recommended for new work)

This is a wrapper around HttpWebRequest. Compare with HttpClient.

Available in: .NET Framework 1.1+, NET Standard 2.0+, and .NET Core 2.0+.

In some circumstances (.NET Framework 4.5-4.8), if you need to do a HTTP request synchronously, WebClient can still be used.

using System.Net;
using System.Collections.Specialized;


  • POST

      using (var client = new WebClient())
    {
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
    }
  • GET

      using (var client = new WebClient())
    {
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
    }

HTTP request GET/POST

So there are quite a few ways to send data and "things" from one web page to the next.

Session() is certainly one possible way.

Another is to use parameters in the URL you thus often see that on many web sites

Even as I write this post - we see the URL on StackOverFlow as this:

stackoverflow.com/questions/66294186/http-request-get-post?noredirect=1#comment117213494_66294186

So, the above is how stack overflow is passing values.

So session() and paramters in the URL os common.

However, asp.net net has a "feature" in which you can pass the previous page to the next. So then it becomes a simple matter to simply pluck/get/grab/use things from that first page in the next page you loaded. so this feature is PART of asp.net, and it will do all the dirty work of passing that previous page for you!!!

Hum, I wonder if people have to ever pass and get values from the previous page? I bet this most common idea MUST have been dealt with, right? And not only is this a common thing say like how human breathe air? It also a feature of asp.net.

So, a REALLY easy approach is to simply when you click on a button, and then jump to the next page in question? Well, if things are setup correctly, then you can simple use the "previous" page!!!

You can do this on page load:

if (IsPostBack == false)
{
TextBox txtCompay = PreviousPage.FindControl("txtCompnay");
Debug.Print("Value of text box company on prevous page = " + txtCompay.Text);
}

This approach is nice, since you don't really have to decide ahead of time if you want 2 or 20 values from controls on the previous page - you really don't care.

How does this work?

The previous page is ONLY valid based two approaches.

First way:

The button you drop on the form will often have "code behind" that of course jumps or goes to the next page in question.

That command (in code behind) is typical this:

Response.Redirect("some aspx web page to jump to")

The above does NOT pass previous page

However, if you use this:

Server.Transfer("some aspx web page to jump to")

Then the previous page IS PASSED and you can use it!!!!

So in the next page, on page load event, you can use "prevouspage" as per above.

so Server.Transfer("to the next page") WILL ALLOW use of "previous page" in your code.

So you can pick up any control, any value. You can even reference say a gridview and the row the user has selected. In effect the whole previous page is transferred and available for using in "previous page" as per above. You can NOT grab viewstate, but you can setup public methods in that previous page to expose members of viewstate if that also required.

You will of course have to use FindControl, but it is the previous page.

The other way (to allow use of previous page).

You don't use code behind to trigger the jump to the new page (with Server.Transfer()), but you set the post-back URL in the button in that first page. that is WHAT the post-back URL is for!!! (to pass the current page to the post-back URL).

eg this:

   <asp:Button ID="Button1" runat="server" Text="View Hotels"
PostBackUrl="~/HotelGrid.aspx" />

So you use the "post back" URL feature of the button.

Now, when you click on that button, it will jump to the 2nd page, and once again previous page can be used as per above. And of course with post-back URL set, then of course you don't need a code behind stub to jump to that page.

So this is quite much a "basic" feature of asp.net, and is a built-in means to transfer the previous page to the next. Kind of like asp.net "101".

So this perhaps common, in fact MOST COMMON BASIC need to pass values from a previous web page is not only built in, but it is in fact called "prevous page"!!!!!

Rules:

Previous page only works if you use a Server.Transfer("to the page")

Response.Request("to the page") does NOT allow use of previous page.

using the post-back URL of a button (or in fact many other controls) also
have a post-back URL setting - and again if that control has post-back URL, then
again use of previous page is allowed due to that control causing such page
navagation.

The previous page can ONLY be used on the first page load (ispostBack = False).

Using post-back URL in a button of course means a code behind stub is not required for the page jump. And once again, using post-back URL will ensure that page previous can be used in the next page.

However, in those cases in which you don't want to hard code the URL, or perhaps some additonal logic occurs in that button code stub before such navigation to the next page? (or is even to occur??).

Then ok post-back URL is not all that practical, but you can then resort to and use Server.Transfer() in that code behind, and AGAIN this allows use of the built in "previous page".

Just keep in mind that whatever you need/want/will grab from the previous page HAS to occur on the FIRST PAGE load of that page we jumped to. Any additonal button post back and the regular life cycle and use of controls and events in code behind on that page will NOT have use of previous page AFTER the first page load has occurred. (previous page will be null and empty).

How to properly make a http web GET request

If using .NET 6 or higher, please read the warning at the bottom of this answer.


Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.

Here's an example of how you could achieve that.

string html = string.Empty;
string url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}

Console.WriteLine(html);

GET

public string Get(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}

GET async

public async Task<string> GetAsync(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}

POST

Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public string Post(string uri, string data, string contentType, string method = "POST")
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
request.Method = method;

using(Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}

using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}



POST async

Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
request.Method = method;

using(Stream requestBody = request.GetRequestStream())
{
await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
}

using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}

Warning notice: The methods of making a HTTP request outlined within this answer uses the HttpWebRequest class which is deprecated starting from .NET 6 and onwards. It's recommended to use HttpClient instead which this answer by DIG covers for environments that depends on .NET 6+.

Ref: https://learn.microsoft.com/en-us/dotnet/core/compatibility/networking/6.0/webrequest-deprecated

How can I get data from a HTTP post in C# Xamarin?

You can post the parameters in the body of the request.

public static async Task<SwipeDetails> SaveSwipesToCloud() {
//get unuploaded swips
var swipesnotsved = SwipeRepository.GetUnUploadedSwipes();

var client = new HttpClient() {
BaseAddress = new Uri(URL)
};
var requestUri = "SaveSwipeToServer";

//send it to the cloud
foreach (var item in swipesnotsved) {

//create the parameteres
var data = new Dictionary<string, string>();
data["locationId"] = item.LocationID;
data["userId"] = item.AppUserID;
data["ebCounter"] = item.SwipeID;
data["dateTimeTicks"] = item.DateTimeTicks;
data["swipeDirection"] = item.SwipeDirection;
data["serverTime"] = item.IsServerTime;

var body = new System.Net.Http.FormUrlEncodedContent(data);

var response = await client.PostAsync(requestUri, body);

//the content needs to update the record in the SwipeDetails table to say that it has been saved.
var content = await response.Content.ReadAsStringAsync();
}
return null;
}

How to Get the HTTP Post data in C# - FiddlerCore?

Provided the session parameter is for a POST request you would get the body of the request in the sess.GetRequestBodyAsString();

private void FiddlerApplication_AfterSessionComplete(Session sess) {
if (sess == null || sess.oRequest == null || sess.oRequest.headers == null)
return;

string reqHeaders = sess.oRequest.headers.ToString(); //request headers
var reqBody = sess.GetRequestBodyAsString();//get the Body of the request
}

Sending a POST request to a URL from C#

You have to create a request stream and write to it, this link here has several ways to do this either with HttpWebRequest, HttpClient or using 3rd party libraries:

Posting data using C#



Related Topics



Leave a reply



Submit