Api POST from code behind - c#

I want to post an object using an API call. I'm getting the data using the following code in my codebehind
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/receipt/" + jID).Result;
if (response.IsSuccessStatusCode)
{}
I would like to know there is any code equivalent to POST for this.

POST using Form:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Key1", "Value1"));
postData.Add(new KeyValuePair<string, string>("Key2 ", "Value2"));
HttpContent content = new FormUrlEncodedContent(postData);
var response = client.PostAsync("api/receipt/" + jID, content)
if (response.IsSuccessStatusCode)
{}
POST using JSON, assume you have Dto class:
var client = new HttpClient();
var dto = new Dto {Pro1 = "abc"};
var reponse = client.PostAsJsonAsync("api/receipt/" + jID, dto).Result;
if (reponse.IsSuccessStatusCode)
{}

The best way for you is to use a third-party library, like RestSharp
The simple way to post something to your api via RestSharp will look like that:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using RestSharp;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
public class SimpleConnector
{
private CookieContainer _cookieJar = new CookieContainer();
private RestClient client = new RestClient();
public string TwitterAuthenticate(string user, string pass)
{
client.CookieContainer = _cookieJar;
//RestClient client = new RestClient("https://twitter.com");
IRestRequest request = new RestRequest("https://twitter.com/", Method.GET);
client.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0";
client.AddDefaultHeader("Accept", "*/*");
//request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
//request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
//request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content;
Match m = Regex.Match(content, #"name=""authenticity_token""\s*value=""(.*?)"">");
string authenticity_token = m.Groups[1].Value;
request = new RestRequest("https://twitter.com/sessions", Method.POST);
request.AddParameter("session[username_or_email]", user);
request.AddParameter("session[password]", pass);
request.AddParameter("return_to_ssl", "true");
request.AddParameter("scribe_log", "");
request.AddParameter("redirect_after_login", "/");
request.AddParameter("authenticity_token", authenticity_token);
response = client.Execute(request);
content = response.Content;
return content;
}

Yes, you can do this way:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);
You could either use one of these methods as given below as per your requirement:
Task<HttpResponseMessage> response = client.PostAsJsonAsync();
OR
Task<HttpResponseMessage> response = client.PostAsXmlAsync();
OR
Task<HttpResponseMessage> response = client.PostAsync();
Hope this helps!

Related

Requesting OAuth Token from Zoom API Shortens the access_token attribute, but does not in Postman

The access_token is always 632 characters long, and when I test it in Postman it works fine
Postman Code:
using System;
using RestSharp;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
var client = new RestClient("https://zoom.us/oauth/token?account_id=VfdA06Q9TQe31jH7oRutuQ&grant_type=account_credentials");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic ####");
request.AddHeader("Cookie", "####");
var body = #"";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
I have a limitation that prevents me from using RestSharp. As such, I am using System.Net.Http in my application, but the access_token is always 533 characters long. I get unauthorized response whenever I use that token which is what alerted me that something may be wrong with it.
System.Net.Http Code
using System;
using System.Collections.Generic;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApp_Test_ZoomCreateMeeting
{
class Program
{
static void Main(string[] args)
{
//Get current token age
// Get the get credentials
// Build the request body
var authRequestBody = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", "####"),
new KeyValuePair<string, string>("client_secret", "####")
});
// Set up the HTTP client
var authClient = new HttpClient();
authClient.BaseAddress = new Uri("https://zoom.us/");
// Send the request and get the response
HttpResponseMessage authResponse = authClient.PostAsync("oauth/token", authRequestBody).Result;
string content = authResponse.Content.ReadAsStringAsync().Result;
long contentLength = authResponse.Content.Headers.ContentLength ?? 0;
string responseContent = authResponse.Content.ReadAsStringAsync().Result;
// Parse the JSON response
JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(responseContent);
// Create an instance of JsonSerializerSettings and set the ReferenceLoopHandling property to Ignore
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// Serialize the jsonResponse object using the JsonSerializerSettings object
string serializedJsonResponse = JsonConvert.SerializeObject(jsonResponse, serializerSettings);
// Extract the access_token property (value<t>)
string currentToken = jsonResponse["access_token"].Value<string>();
Console.WriteLine("Current Token: " + currentToken);
}
}
}
Any ideas on a solution here?
I tried to request an OAuth token from the Zoom API, and though I received one, the access_token attribute is being cut short

How do I pass X-HTTP-METHOD-Override Header to C#s HttpClient

I try to update a field using REST in C#. Using PatchAsync did not work so far, so I'm trying to use PUT instead, but now I need to pass the X-HTTP-METHOD-Override Header and I have no idea how to do this.
I've looked at the available headers for the DefaultRequestHeaders, but I could not find anything.
This is what I have got so far:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BASEURL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = CreateAuthHeader();
var requestBody = new Dictionary<string, string>
{
{ "price", price.ToString() }
};
var jsonRequest = JsonConvert.SerializeObject(requestBody);
var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json-patch+json");
var response = new HttpResponseMessage();
response = await client.PutAsync($"{APIBASE}/data/ProductAttribute/{attributeId}", content).ConfigureAwait(false);
This should work like normal:
client.DefaultRequestHeaders.Add("X-HTTP-METHOD-Override", "PATCH");
I'm assuming you want PATCH as verb.

POST Request with json in c#

I am attempting to do a POST request which I have got working through Postman but I am getting a 400 error when done from code.
I am trying to reach the POST endpoint from here: http://developer.oanda.com/rest-live-v20/order-ep/
Here is my code, does anything look incorrect or have I missed anything?
public void MakeOrder(string UID)
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
using (WebClient client = new WebClient())
{
client.Headers.Add("Authorization", "Bearer 11699873cb44ea6260ca3aa42d2898ac-2896712134c5924a25af3525d3bea9b0");
client.Headers.Add("Content-Type", "application/json");
client.UploadString(url, body);
}
}
I'm very new to coding so apologies if it is something very simple.
use HttpClient from System.Net.Http:
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using (var httpClient = new HttpClient())
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
var content = new StringContent(body , Encoding.UTF8, "application/json");
var result = httpClient.PostAsync(url, content).Result;
var contents = result.Content.ReadAsStringAsync();
}
I would suggest you to use HttpClient over WebClient. You can find here the difference.
using (var httpClient = new HttpClient())
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
var content = new StringContent(body, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTIzMDY0NTQsImlzcyI6IlRlc3QuY29tIiwiYXVkIjoiVGVzdC5jb20ifQ.c-3boD5NtOEhXNUnzPHGD4rY1lbEd-pjfn7C6kDPbxw");
var result = httpClient.PostAsync(url, content).Result;
var contents = result.Content.ReadAsStringAsync();
}

include raw text in http get request in c# backend code

I have this code:
client.BaseAddress = new Uri("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/vendor/70?minorversion=8");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "bLpuw.vjbvIP_P7Vyj4ziSGa3Ohg");
using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8").Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}
Per the quickbooks api Postman sample they include raw text query in the http post action.
Example:
How can I include the raw text in my c# post request?
You need to pass content to PostAsync method just like this
var myContent = "your string in here";
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8",bytecontent).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}
Create a StringContent() with the text in it and pass it to the PostAsync().
You might need to check what Content-Type header is expected and pass that to the StringContent constructor as well.
E.g.
using (var requestContent = new StringContent(“any text”, Encoding.UTF8, “text/plain”))
{
... httpClient.PostAsync(url, requestContent)...
}
client.BaseAddress = new Uri("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/vendor/70?minorversion=8");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "bLpuw.vjbvIP_P7Vyj4ziSGa3Ohg");
var postContent = new StringContent("myContent");
using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8", postContent).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}
Also, please be aware that you have some wrong use of the Async methods, you should always await instead of using the blocking Result property from the task.

Set Authorization/Content-Type headers when call HTTPClient.PostAsync

Where can I set headers to REST service call when using simple HTTPClient?
I do :
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{"id", "111"},
{"amount", "22"}
};
var content = new FormUrlEncodedContent(values);
var uri = new Uri(#"https://some.ns.restlet.uri");
var response = await client.PostAsync(uri, content);
var responseString = await response.Content.ReadAsStringAsync();
UPD
Headers I want to add:
{
"Authorization": "NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3",
"Content-Type": "application/json"
}
Should I do the following?
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3","Content-Type":"application/json");
The way to add headers is as follows:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
Or if you want some custom header:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("HEADERNAME", "HEADERVALUE");
This answer has SO responses already, see below:
Adding headers when using httpClient.GetAsync
Setting Authorization Header of HttpClient
UPDATE
Seems you are adding two headerrs; authorization and content type.
string authValue = "NLAuth nlauth_account=5731597_SB1,nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3";
string contentTypeValue = "application/json";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue);
client.DefaultRequestHeaders.Add("Content-Type", contentTypeValue);
I know this was asked a while ago, but Juan's solution didn't work for me.
(Also, pretty sure this question is duplicated here.)
The method that finally worked was to use HttpClient with HttpRequestMessage and HttpResponseMessage.
Also note that this is using Json.NET from Newtonsoft.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace NetsuiteConnector
{
class Netsuite
{
public void RunHttpTest()
{
Task t = new Task(TryConnect);
t.Start();
Console.WriteLine("Connecting to NS...");
Console.ReadLine();
}
private static async void TryConnect()
{
// dummy payload
String jsonString = JsonConvert.SerializeObject(
new NewObj() {
Name = "aname",
Email = "someone#somewhere.com"
}
);
string auth = "NLAuth nlauth_account=123456,nlauth_email=youremail#somewhere.com,nlauth_signature=yourpassword,nlauth_role=3";
string url = "https://somerestleturl";
var uri = new Uri(#url);
HttpClient c = new HttpClient();
c.BaseAddress = uri;
c.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
req.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
HttpResponseMessage httpResponseMessage = await c.SendAsync(req);
httpResponseMessage.EnsureSuccessStatusCode();
HttpContent httpContent = httpResponseMessage.Content;
string responseString = await httpContent.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}
class NewObj
{
public string Name { get; set; }
public string Email { get; set; }
}
}
The other answers do not work if you are using an HttpClientFactory, and here's some reasons why you should. With an HttpClientFactory the HttpMessages are reused from a pool, so setting default headers should be reserved for headers that will be used in every request.
If you just want to add a content-type header you can use the alternate PostAsJsonAsync or PostAsXmlAsync.
var response = await _httpClient.PostAsJsonAsync("account/update", model);
Unfortunately I don't have a better solution for adding authorization headers than this.
_httpClient.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), $"Bearer {bearer}");
On dotnet core 3.1 trying to run the top answer:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-Type", "application/x-msdownload");
threw an exception: System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
What worked for me was to instead set HttpContent.Headers -> HttpContentHeaders.ContentType property with a MediaTypeHeaderValue value:
HttpClient client = new HttpClient();
var content = new StreamContent(File.OpenRead(path));
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-msdownload");
var post = client.PostAsync(myUrl, content);
I prefer to cache the httpClient so I avoid setting headers which could affect other requests and use SendAsync
var postRequest = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
postRequest.Headers.Add("Content-Type", "application/x-msdownload");
var response = await httpClient.SendAsync(postRequest);
var content = await response.Content.ReadAsStringAsync();

Categories

Resources