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>");
}
How can I get post data for asp.net c#
Try this
string[] keys = Request.Form.AllKeys;
var value = "";
for (int i= 0; i < keys.Length; i++)
{
// here you get the name eg test[0].quantity
// keys[i];
// to get the value you use
value = Request.Form[keys[i]];
}
Getting a POST variable
Use this for GET values:
Request.QueryString["key"]
And this for POST values
Request.Form["key"]
Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:
Request["key"]
Another thing to note (if you need it) is you can check the type of request by using:
Request.RequestType
Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack
will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.
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");
}
Get the POST data back on Web API
There is a mismatch between the class you want and the data being sent.
Your desired class looks like this
public class UploadLogsIn {
public byte[] logData { get; set; }
public int aLogs { get; set; }
}
But the data being sent looks like this
{"UploadLogsIn": [{"aLogs": 10}]}
Which when deserialized looks like this
public class UploadLogsIn
{
public int aLogs { get; set; }
}
public class RootObject
{
public IList<UploadLogsIn> UploadLogsIn { get; set; }
}
See the difference?
To get the model to bind to this action
[HttpPost]
public bool UploadLogs([FromBody]UploadLogsIn logs) {
return true;
}
The data sent would have to look like this
{"aLogs": 10}
How to get POST data in WebAPI?
From answer in this question:
How to get Json Post Values with asp.net webapi
Autoparse using parameter binding; note that the
dynamic
is made up ofJToken
, hence the.Value
accessor.public void Post([FromBody]dynamic value) {
var x = value.var1.Value; // JToken
}Read just like
Request.RequestUri.ParseQueryString()[key]
public async Task Post() {
dynamic obj = await Request.Content.ReadAsAsync<JObject>();
var y = obj.var1;
}Same as #2, just not asynchronously (?) so you can use it in a helper method
private T GetPostParam<T>(string key) {
var p = Request.Content.ReadAsAsync<JObject>();
return (T)Convert.ChangeType(p.Result[key], typeof(T)); // example conversion, could be null...
}
Caveat -- expects media-type application/json
in order to trigger JsonMediaTypeFormatter
handling.
How receive data from POST in asp.net MVC
When your are posting data to method in C# you need to have class defined with same parameters in your post method.
In your case your method will become
[HttpPost]
public ActionResult save(Person person)
{
//Here your need to access person object to get the data
string name = person.name;
return Json(name, JsonRequestBehavior.AllowGet);
}
Now class person will be representation of what your sending from your client.
Again in your case Person class will be like
class Person
{
public int ID {get; set;}
public string name {get; set;}
public string lastname {get; set;}
}
So as mentioned in comments creating class Person
in completely optional and you can skip that it just on of best practice. In that case your post method will look like
[HttpPost]
public ActionResult save(Object person)
{
//Here your need to access person object to get the data
string name = person.name;
return Json(name, JsonRequestBehavior.AllowGet);
}
Related Topics
ASP.NET 2012 Unobtrusive Validation with Jquery
How to Remove Accents on a String
Selecting a Textbox Item in a Listbox Does Not Change the Selected Item of the Listbox
Query Microsoft Access Mdb Database Using Linq and C#
Is There Windows System Event on Active Window Changed
Get Thumbnail Image of Video File in C#
Watermark in System.Windows.Forms.Textbox
Can You Specify Format for Xmlserialization of a Datetime
Hashset That Preserves Ordering
-Event- Can Only Appear on the Left Hand Side of += or -=
ASP.NET Core Metadatatype Attribute Not Working
Can You Have a Property Name Containing a Dash