Building post HttpClient request in C# with Bearer Token - c#

I'm not really a C# expert and I have a post httpRequest in C# to develop and for this I created this method that takes a Uri, an object and a bearer token.
This method aims to build the calling request:
private HttpClient client = new HttpClient();
public async Task<UserResponse> CreateUser(Uri url, UserRequest userRequest, string token)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
string requestObject = JsonConvert.SerializeObject(userRequest);
Console.WriteLine("My Object: " + requestObject);
var req = new HttpRequestMessage(HttpMethod.Post, url);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
req.Content = new StringContent(
requestObject,
Encoding.UTF8,
"application/json"
);
Console.WriteLine(req.ToString());
var response = await client.SendAsync(req);
string output = await response.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.DeserializeObject(output));
UserResponse returnValue = JsonConvert.DeserializeObject<UserResponse>(output);
return returnValue;
}
My issue is that i'm not sure I'm passing correctly my header content. The return response is an error message telling I'm not authenticated.
Thanks

you have to add token this way:
var baseAddress = "http://....";
var api = ".....";
client.BaseAddress = new Uri(baseAddress);
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var postData = JsonConvert.SerializeObject(userRequest);
contentData = new StringContent(postData, Encoding.UTF8, "application/json");
var response = await client.PostAsync(baseUrl + api, contentData);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<UserResponse>(stringData);
}
else
{
}

Related

HttpClient request no response

I am not getting any response - no error, no bad request status, etc. - when I send a post request to this API route. postData is simply a JSON object. The funny thing here is this: When i send post data as a string instead of an object, I can get a response.
View the code below:
[HttpPost]
[Route("api/updateStaffs/")]
public async Task<object> UpdateStaff([FromBody] object postData)
{
string _apiUrl = "http://localhost:5000/system/getToken";
string _baseAddress = "http://localhost:5000/system/getToken";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage = await client.PostAsync(_apiUrl, new StringContent(postData.ToString(), Encoding.UTF8, "application/json"));
if (responseMessage.IsSuccessStatusCode)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = responseMessage.Content;
return ResponseMessage(response);
}
}
return NotFound();
}
No response:
var postData = new {
user = "test"
pass = "hey"
};
var responseMessage = await client.PostAsync(_apiUrl, new StringContent(postData.ToString(), Encoding.UTF8, "application/json"));
OR
var responseMessage = await client.PostAsync(_apiUrl, new StringContent("{}", Encoding.UTF8, "application/json"));
Will get response:
var responseMessage = await client.PostAsync(_apiUrl, new StringContent("blahblah", Encoding.UTF8, "application/json"));
The receiving API is a third-party application so I am unable to verify if this error is on the other end.
Thanks.
If you dont want to use PostAsJsonAsync
You need to serialize your anonymous type to JSON, the most common tool for this is Json.NET
var jsonData = JsonConvert.SerializeObject(postData);
Then you need to construct a content object to send this data, here we can use ByteArrayContent but you can use a different type
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var byteContent = new ByteArrayContent(buffer);
Then send the request
var responseMessage = await client.PostAsync(_apiUrl, byteContent);
Figured out the issue. Have to use HttpVersion10 instead of HttpVersion11.

How to send a post request in dotnet with a list of request headers

public static async Task<HttpResponseMessage> Post(string endPoint, string data){
HttpContent c = new StringContent(data, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(VodapayBaseUrl + endPoint),
Content = c,
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result = await client.SendAsync(request).ConfigureAwait(false); // The code fails here
if (result.IsSuccessStatusCode)
{
Console.WriteLine("got here");
return result;
}
else
{
Console.WriteLine("failled");
return result;
}
}
// return result;
}
Here is an updated version:
public static async Task Post()
{
using (var httpClient = new HttpClient())
{
var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";
httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Successful");
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Not successful");
}
}
}
class Program
{
private static void Main(string[] args)
{
Post().Wait();
Console.WriteLine();
}
}
}
Can someone please help with this I am new to c# and relatively new to coding. I am trying to send a request using httpclient I need to send data in a json format I also need to send a list of headers. How can I do this and also return json data at the end your help will be appreciated.I am getting an error when i run this:
Your code isn't far off, here's an example that I had in one of my projects ...
using (var httpClient = new HttpClient())
{
var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";
// Setup the HttpClient and make the call and get the relevant data.
httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Successful");
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Not successful");
}
}
... obviously, it has varying degrees of thought for the scenario at hand but just adapt it as need be.

Calling an api using httpClient PostAsync - 400 Bad Request

There has been a lot of similar questioning on this one but I could not get any answers working for me..
I am calling another api Post request from my controller..but I get a 400 bad request all the time..
public async Task<JsonResult> TestSCIMPost(AppAuth auth)
{
//Method 3:
HttpClient client = new HttpClient();
var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
var content = new StringContent(jsonRequest);
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");
HttpResponseMessage response = await client.PostAsJsonAsync(
URL, content);
return new JsonResult(response);
}
curl
curl -X POST "https://localhost:5001/api/Employee/api/Employee/TestSCIMPost" -H "accept: /" -H "Content-Type: application/json-patch+json" -d "{"client_id":"xyz","grant_type":"cc","client_secret":"abc","scope":"read"}"
I have tried a couple of other ways that I am listing below..
public async Task<JsonResult> TestSCIMPost(AppAuth auth)
{
/*var response = string.Empty;
var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(jsonRequest);
var content = new ByteArrayContent(messageBytes);
//HttpContent c = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");
//content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
using (var client = new HttpClient())
{
//client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result = await client.PostAsync(URL, content);
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}*/
//Method:2
//HttpClient client = new HttpClient();
//client.BaseAddress = new Uri(URL);
//client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
//var requestMessage = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
//var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");
//content.Headers.Remove("Content-Type");
//content.Headers.Add("Content-Type", "application/json");
//HttpResponseMessage result = await client.PostAsync(URL, content);
return new JsonResult(response);
}
The body is coming from auth (frontend that i am serializing and adding in my request)
What's going wrong here? Is it utf-encoding? how to fix?
One reason this can happen is if you are posting content in the body (as you are doing) where the parser expects to find it in the query.
So if you have something like this:
string url = "https://localhost:5001/api/Employee/TestSCIMPost";
var content = new StringContent("{\"client_id\":\"xyz\",\"grant_type\":\"cc\"}");
HttpResponseMessage response = await client.PostAsync(url, content);
Try changing it to this:
string url = "https://localhost:5001/api/Employee/TestSCIMPost?client_id=xyz&grant_type=cc";
var content = new StringContent("");
HttpResponseMessage response = await client.PostAsync(url, content);

How to attachment a file to an item in Sharepoint using Microsoft.Graph

Microsoft.Graph Sharepoint api allows to update list item https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/listitem_update using PATCH request. But how to generate a correct request?
using (HttpClient pacthClient = new HttpClient())
{
var mediaType = new MediaTypeWithQualityHeaderValue("application/json");
pacthClient.DefaultRequestHeaders.Accept.Add(mediaType);
pacthClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userToken);
using (HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod("PATCH"), $"{uri}/{id}"))
{
requestMessage.Content = byteArrayContent ???
using (HttpResponseMessage responseMessage = await pacthClient.SendAsync(requestMessage))
{
}
}
}
string addItemJsonString = "{\"name\":\"Test Visit\"}";
string requestUrl = "https://graph.microsoft.com/v1.0/sites/{siteID}/lists/{listID}/items/{itemID}/fields";
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("PATCH"), requestUrl);
message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
//set the request body
message.Content = new StringContent(addItemJsonString);
HttpResponseMessage response = await client.SendAsync(message);
if (response.IsSuccessStatusCode)
{
responseString = await response.Content.ReadAsStringAsync();
}
else
responseString = "Error in response";

Make a post Request with azure new rest api (ressource manager)

I want to start my VM using the post Uri as described here https://msdn.microsoft.com/en-us/library/azure/mt163628.aspx
Since i don't have body in my request i get 403 frobidden. I can make a get Request without problem. Here is my code
public void StartVM()
{
string subscriptionid = ConfigurationManager.AppSettings["SubscriptionID"];
string resssourcegroup = ConfigurationManager.AppSettings["ressourgroupename"];
string vmname = ConfigurationManager.AppSettings["VMName"];
string apiversion = ConfigurationManager.AppSettings["apiversion"];
var reqstring = string.Format(ConfigurationManager.AppSettings["apirestcall"] + "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/start?api-version={3}", subscriptionid, resssourcegroup, vmname, apiversion);
string result = PostRequest(reqstring);
}
public string PostRequest(string url)
{
string content = null;
using (HttpClient client = new HttpClient())
{
StringContent stringcontent = new StringContent(string.Empty);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string token = GetAccessToken();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = client.PostAsync(url, stringcontent).Result;
if (response.IsSuccessStatusCode)
{
content = response.Content.ReadAsStringAsync().Result;
}
}
return content;
}
i've also tried this in the PostRequest
var values = new Dictionary<string, string>
{
{ "api-version", ConfigurationManager.AppSettings["apiversion"] }
};
var posteddata = new FormUrlEncodedContent(values);
HttpResponseMessage response = client.PostAsync(url, posteddata).Result;
with url=string.Format(ConfigurationManager.AppSettings["apirestcall"] + "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/start", subscriptionid, resssourcegroup, vmname);
I Get 400 Bad request
I found the solution. Needed to add role in Azure to allow starting/stopping the VM. That is why i received 4.3 forbidden.
Thank you

Categories