C# Web API Sending Body Data in Http Post Rest Client

C# Web API Sending Body Data in HTTP Post REST Client

Why are you generating you own json?

Use JSONConvert from JsonNewtonsoft.

Your json object string values need " " quotes and ,

I'd use http client for Posting, not webclient.

using (var client = new HttpClient())
{
var res = client.PostAsync("YOUR URL",
new StringContent(JsonConvert.SerializeObject(
new { OBJECT DEF HERE },
Encoding.UTF8, "application/json")
);

try
{
res.Result.EnsureSuccessStatusCode();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

C# - Body content in POST request

Thanks to this and this, I finally found the solution to send post requests with headers AND body content. Here's the code:

        var cl = new HttpClient();
cl.BaseAddress = new Uri("< YOUR URL >");
int _TimeoutSec = 90;
cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
string _ContentType = "application/x-www-form-urlencoded";
cl.DefaultRequestHeaders.Add(key, value);
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
cl.DefaultRequestHeaders.Add("key", "value");
cl.DefaultRequestHeaders.Add("key", "value");
var _UserAgent = "d-fens HttpClient";
cl.DefaultRequestHeaders.Add("User-Agent", _UserAgent);

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("key of content", "value"));
var req = new HttpRequestMessage(HttpMethod.Post, "http://www.t-lab.fr:3000/add_tips") { Content = new FormUrlEncodedContent(nvc) };
var res = cl.SendAsync(req);

Send string in body as a POST REST call (javascript to Asp.Net Core)

Even though @joacoleza's answer does work, it was not feasible in one of my cases (the object that I am receiving is huge (~200 fields) and I only need to extract 5. Also it might change quite often and I'd have to adjust my object even though I am not really touched by the changes.

I finally found the solution myself:

As already said, .Net tries to parse the content of the body to the requested object:

public ActionResult Post([FromBody] string value)

This requires a string object. If we want to send a JSON and then parse it, we can send it in this way: '{"field":"value", "field2":"value2"}'

But if we do not control the content of the body in the request and we are receiving a X object (or different object that we might want to parse in run-time) we just need to change the type of the function argument to JObject:

public ActionResult Post([FromBody] JObject value)

The parsed JObject will contain the whole structure of the JSON, but it will still give us enough freedom to do whatever we want with the raw version, without having to cast it to a POCO just for the transition: var amount = value["amount"];

This is what I was looking for.

Angular post request to c# web api 2 RESTful web service

You are passing an anonymous object with properties "UserId" and "Password".
Make a Data Contract class which has those 2 properties as strings and use it in the parameters of your REST method.

public IHttpActionResult LoginReq([FromBody] User user) { ... }

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");
    }

MVC API sending data in the body

Is there any specific reason for you using WebRequest instead of HttpClient? If you're not doing any FTP work and you're using .NET Framework 4.5+ or .NET Core you're better off migrating to HttpClient as it gives you easier usage flow, comes with async support out of the box and is quite easier to mock and test, while giving you more functionality on top of that. Overall, it is the modern API for making requests from .NET.

public async Task<T> Post<T>(object model) // use actual model type instead of type object
{
var url = "Specify URL";
var token = "Specify Token";

var payload = JsonSerializer.Serialize(model);

// Preferably get the instance from dependency injection or hoist it as a private variable in the class body.
// In any case, don't recreate it like we're doing here.
var client = new HttpClient();

var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);

requestMessage.Headers.Add("Authorization", $"Bearer {token}");
requestMessage.Content = new StringContent(payload, Encoding.UTF8, "application/json");

var responseMessage = await client.SendAsync(requestMessage);

if (responseMessage.IsSuccessStatusCode)
{
var result = await responseMessage.Content.ReadAsStringAsync();

return JsonSerializer.Deserialize<T>(result);
}
else
{
// Handle error result
throw new Exception();
}
}


Related Topics



Leave a reply



Submit