How to set content in PostAsync method - c#

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

Related

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

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

How to convert curl request to HttpClient having --resolve

I have a following curl request
curl -X POST -D- --insecure -H "ApiKey: $api_key" https://api.myapi.com/service/12345/purge/12345--resolve [http://api.myapi.com:443:11.112.121.194/]api.myapi.com:443:11.112.121.194
I want to convert that over to HttpClient.
var baseUrl = "https://api.myapi.com";
HttpClient httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("ApiKey", "api_key");
var request = new HttpRequestMessage(HttpMethod.Post, $"service/{12345}/purge/{12345}");
request.Content = new StringContent(null, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
How do I add --resolve parameter to HttpRequest?

Passing Authorization Header in multiple redirects of HttpClient

I'm sending a get request to the server, the server is redirecting to 4 furthur call and then returns the response.
HttpClient gives the exception, no authorization token is provided.
Can you tell me, how to pass the same authorization token on multiple redirects? It works fine if I set "AllowAutoRedirect=false" & returns RanToComplation Status.
Here is my method :
static async Task CallWebAPIAsync()
{
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.UseDefaultCredentials = true;
webRequestHandler.AllowPipelining = true;
webRequestHandler.AllowAutoRedirect = true;
using (var client = new HttpClient(webRequestHandler))
{
client.BaseAddress = new Uri("https://apirequest");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
client.Timeout = TimeSpan.FromSeconds(30000);
//GET Method
var response = await client.GetAsync("user").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseresult = await response.Content.ReadAsStringAsync();
Console.WriteLine("Id:{0}\tName:{1}", responseresult);
}
else
{
Console.WriteLine("Internal server Error");
}
}
I think the problem may be related to this
Authorization headers must be stripped on redirects. I'm currently trying to figure out how to work around it.
I was missing the delegation handler, which will handle the redirects.
https://stackoverflow.com/a/19493338/3459965
this link helps me
Updated Code is:
static async Task CallWebAPIAsync()
{
HttpClientHandler clientHandler = new HttpClientHandler();
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.UseDefaultCredentials = true;
webRequestHandler.AllowPipelining = true;
webRequestHandler.AllowAutoRedirect = false;
webRequestHandler.Credentials = CredentialCache.DefaultCredentials;
GlobalRedirectHandler globalRedirectHandler = new GlobalRedirectHandler() { InnerHandler = webRequestHandler };
using (var client = new HttpClient(globalRedirectHandler))
{
client.BaseAddress = new Uri("https://apitest");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
client.Timeout = TimeSpan.FromSeconds(30000);
//GET Method
var response = await client.GetAsync("user").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseresult = await response.Content.ReadAsStringAsync();
Console.WriteLine("Id:{0}\tName:{1}", responseresult);
}
else
{
Console.WriteLine("Internal server Error");
}
}
}

Can't get body data on server using C# code

I'm trying to send a json content inside the body. But unfortunately, I don't get the data in the server. Same data is received using postman tool.
Here is the code I'm running
private string callAPI(string function, string content)
{
using (var httpClient = new HttpClient())
{
string url = function;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", txt_sessionKey.Text);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
httpClient.BaseAddress = new Uri(baseUrlV2);
var json = new StringContent(content, Encoding.UTF8, "application/json");
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Put,
RequestUri = new Uri(baseUrlV2+function),
Content = json
};
HttpContent contentRes = httpClient.SendAsync(request).Result.Content;
return contentRes.ReadAsStringAsync().Result;
}
}
What am I missing here?

Categories