Calling an api using httpClient PostAsync - 400 Bad Request - c#

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

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.

Building post HttpClient request in C# with Bearer Token

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
{
}

why An error is created when creating the token

public static void CreateToken()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("grant_type", "client_credentials");
var UserPassJson = "{\"username\": \"mucode\",\"password\": \"mypassword\"}";
HttpContent content = new StringContent(UserPassJson, Encoding.UTF8, "application/json");
var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
Console.WriteLine(responseString);
}
}
why response.IsSuccessStatusCode Showing status code 401? What causes the malfunction?
What action does cause success?
The documentation specifies that you should pass the username and password using basic authentication and that you should pass a form-encoded body containing grant_type=client_credentials.
At the moment your code adds grant_type as a header, and posts the username and password as a JSON object in the body.
Correcting your code to do it the way the documentation says, we get:
HttpClient client = new HttpClient();
byte[] authBytes = System.Text.Encoding.ASCII.GetBytes("mucode:mypassword");
string base64Auth = Convert.ToBase64String(authBytes);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64Auth);
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "client_credentials") });
var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
Console.WriteLine(responseString);
}
P.S. I recommend reading You're using HttpClient wrong and it is destabilizing your software and the follow-up You're (probably still) using HttpClient wrong and it is destabilizing your software. I also recommend making this method async and making the chain all the way up async too.

How to set content in PostAsync method

When the method is called, it returns Status code: not found. I'm sure that the uri is correct, so i think that the problem is the content. This is the api called by terminal:
curl --request POST 'https://api.uniparthenope.it/user/radius/auth' --data "user=xxxxxxxxxx" --data "passw=xxxxxxxxxx"
and this is my code:
public async Task<string> Login()
{
client = new HttpClient();
client.BaseAddress = new Uri("https://api.uniparthenope.it");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.MaxResponseContentBufferSize = 256000;
content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("user",Username),
new KeyValuePair<string,string>("passw",Password)
});
content.Headers.ContentType.CharSet = "UTF-8";
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await client.PostAsync("user/radius/auth", content);
//return response.RequestMessage.ToString();
return response.StatusCode.ToString();
}

Categories