Send httpcontent with PostAsync gives Internal Server Error - c#

To send data as querystring in PostAsync Method, I am using following approach. but i am getting Inernal Server Error.
HttpResponseMessage response;
string stringContent = "{ 'request_key': 'ABCD1234', 'request_code': 'CODE', 'request_type':'ID_type' }";
using(var client = new HttpClient()) {
client.BaseAddress = new Uri(SubscriptionUtility.GetConfiguration("BaseURI"));
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(SubscriptionUtility.GetConfiguration("ContentType")));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", SubscriptionUtility.GetConfiguration("BasicAuthentication"));
response = await client.PostAsync(SubscriptionUtility.GetConfiguration("SubscriptionAPI"), stringContent, new JsonMediaTypeFormatter());
if(response.IsSuccessStatusCode) {
var dataObjects = JsonConvert.DeserializeObject<List<TestClass>>(response.Content.ReadAsStringAsync().Result);
//foreach(var d in dataObjects) {
//}
}
}
But When i send the request through fiddler, Its working fine. Here is my fiddler request
User-Agent: Fiddler
Content-Type: application/json; charset=utf-8
Host: testapi.com
Content-Length: 93
Authorization: Basic 12fbe6e1f63d832aa33232323
Post Data:
{
"request_key":"ABCD1234",
"request_code":"CODE",
"request_type":"ID_type"
}

I have achieved the desire functionality using following approach
Post Request
using(var client = new HttpClient()) {
client.BaseAddress = new Uri(SubscriptionUtility.GetConfiguration("BaseURI"));
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(SubscriptionUtility.GetConfiguration("ContentType")));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", SubscriptionUtility.GetConfiguration("BasicAuthentication"));
var values = new Dictionary<string, string>
{
{ "request_key", "ABCD1234" },
{ "request_code", "CODE" },
{ "request_type", "ID_type" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(SubscriptionUtility.GetConfiguration("SubscriptionAPI"), content);
var responseString = await response.Content.ReadAsStringAsync();

Related

C# REST Api always return 401 status code when i am calling API by HttpClient

I am working with Nasdaq Fund Network Data Service first time. i am calling their one of the API where passing user id,pwd and access key but always getting 401 status code. i am not able to figure out what is wrong in my http call. please some one have a look at the code and tell me where i made the mistake for which i am getting 401 status code instead of right response.
here is my sample code where i could not share actual credentials and access key.
giving the code
string url = "sample url";
Uri u = new Uri(url);
string username = "test1";
string password = "test2";
string accessKey = "myaccesskey";
var payload = new Dictionary<string, string>
{
{"username", username},
{"password", password},
{ "accessKey", accessKey}
};
string strPayload = JsonConvert.SerializeObject(payload);
//HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/json");
HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = string.Empty;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
using (var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = u,
Content = c
};
var result = client.SendAsync(request).Result;
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}
This Error i am getting
{StatusCode: 401, ReasonPhrase: 'Check Username/Password or Access
Key', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: {
Pragma: no-cache X-Frame-Options: SAMEORIGIN Cache-Control:
no-cache Date: Wed, 10 Aug 2022 11:55:36 GMT Content-Length: 0
Expires: -1 }}
Try the following in order to extract the JWT token you receive as a response.
var url = "https://nfn.nasdaq.com/servicecall/tempsession";
var formDataDictionary = new Dictionary<string, string>
{
{ "username", "test1"},
{ "password", "test2"},
{ "accessKey", "myaccesskey"}
};
var formData = new FormUrlEncodedContent(formDataDictionary);
using (var client = new HttpClient())
{
var response = await client.PostAsync(url, formData);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
var responseBody = JObject.Parse(result);
var accessToken = responseBody["data']"].Value<string>();
}

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

HttpClient with csrf_token response unauthorized error

so able to do this manually using postman. Two steps involved , first do a Get with UserID/password. From the response get the csrf token attach the same in Another post method. No Authentication required in second call but just token with JSON payload returns the 200 response code.
Now tried these steps in C# and getting UnAuthorized error. Not sure if am attaching the token correct. below is the code.
var awdToken = await getAWDToken();
if (awdToken != null)
{
awdAddUser = await AddAWDUser(awdToken, userDetails);
}
private async Task<string> getAWDToken()
{
using (var client = new HttpClient())
{
string targetUri = string.Empty;
string userId = string.Empty;
string pass = string.Empty;
Dictionary<string, string> _awdConfigs;
_userSecurityWrok.CleintConfiguration.ClientAppConfigs.TryGetValue(string.Concat("AWD", "1"), out _awdConfigs);
if (_awdConfigs != null)
{
_awdConfigs.TryGetValue("AWDShortNameURL", out targetUri);
_awdConfigs.TryGetValue("UserName", out userId);
_awdConfigs.TryGetValue("Password", out pass);
}
client.BaseAddress = new Uri(targetUri);
var byteArray = new UTF8Encoding().GetBytes(userId + ":" + pass);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.ExpectContinue = false;
var response = await client.GetAsync(targetUri).ConfigureAwait(false);
IEnumerable<string> _tokens = response.Headers.GetValues("csrf_token");
var token = _tokens.FirstOrDefault();
var responseInfo = await response.Content.ReadAsStringAsync();
return token;
}
}
private async Task<UpdateResult> AddAWDUser(string awdToken, UserDetail userDetails)
{
UpdateResult userAddresult = new UpdateResult() { Success = false, Errors = new List<string>(), Messages = new List<string>() };
ClientDetails clientData = await _clientWork.GetClientDetails(userDetails.ClientId);
var awdPayLoad = await prepareAWDPayload(userDetails);
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler))
{
string targetUri = string.Empty;
Dictionary<string, string> _awdConfigs;
_userSecurityWrok.CleintConfiguration.ClientAppConfigs.TryGetValue(string.Concat("AWD", "1"), out _awdConfigs);
if (_awdConfigs != null)
{
_awdConfigs.TryGetValue("AWDShortNameURL", out targetUri);
}
client.BaseAddress = new Uri(targetUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("csrf_token", awdToken);
client.DefaultRequestHeaders.Add("Cookie", "csrf_token=" + awdToken);
client.DefaultRequestHeaders.ExpectContinue = false;
var content = new StringContent(awdPayLoad, Encoding.UTF8, "application/json");
var response = await client.PostAsync(targetUri, content).ConfigureAwait(false);
var responseInfo = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
userAddresult.Success = true;
}
else
{
userAddresult.Success = false;
userAddresult.Errors = new List<string> { "AWD returned error as " + response.StatusCode.ToString() };
}
}
return userAddresult;
}
Need to get this working... any idea?
attaching postman dump
POST /devapp/awdServer/awd/services/v1/users/ HTTP/1.1
Host: awdwaldn.nonprod.awdprocess.net:8443
csrf_token: L1HmyGPvEC4GvrOqBioL0Q..
Content-Type: application/json
User-Agent: PostmanRuntime/7.20.1
Accept: */*
Cache-Control: no-cache
Postman-Token: 594c3d97-de46-4fc3-9c2d-1b5f74278e60,8be8e538-267f-4544-b33a-211b2d479b3b
Host: ***** //removed host details
Accept-Encoding: gzip, deflate
Content-Length: 325
Cookie: BIGipServerawdwaldn-nonprod-web-8443-dev-web=454308362.16671.0000; JSESSIONID=8hl6G3gImEf4S71c8CFIzfMd.JVM1
Connection: keep-alive
cache-control: no-cache
{
"userId": "DST1234",
"alias": "DST1234",
"password": "TextAW1#",
"firstName": "chi",
"lastName": "chan",
"workSelect": "1",
"group": "WORK GROUP",
"countryCode": 1,
"earlyTime": "00:00:01",
"lateTime": "23:59:59",
"queue": "N",
"status": "A",
"workSelect": 1
}
I found it. its the cookies. We need to read the cookies from first response and attach it to second one. Issue resolved. thanks for your help.

Creating an issue using JIRA Rest API returns HTTP status code 200 but the issue is not created

I want to create an issue with Jira Rest API using C#
string data = #"{ ""fields"": {
""project"":
{
""key"": ""TOTEM""
},
""summary"": ""just a test"",
""description"": ""Creating of an issue using project keys and issue type names using the REST API"",
""issuetype"": {
""name"": ""Task""
},
""assignee"": { ""name"": ""imane.elbarchi"" }
}
}";
//Console.WriteLine(data);
string uri = "https://proactioneu.ent.cgi.com/rest/api/latest/issue";
System.Net.Http.HttpClient client = new HttpClient();
//Putting URI in client base address.
client.BaseAddress = new Uri(uri);
//Putting the credentials as bytes.
byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
//Putting credentials in Authorization headers.
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
//Putting content-type into the Header.
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
//I am using StringContent because I am creating console application, no any serialize I used for manipulate the string.
var content = new StringContent(data, Encoding.UTF8, "application/json");
System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result;
Console.WriteLine(response);
Console.ReadKey();
}
}
}
and I get a response like:
StatusCode: 200, ReasonPhrase: 'Found', Version: 1.0, Content:
System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
Cache-Control: no-cache
Connection: close
Content-Type: text/html
}
but the issue is not created.
I think it is because of this line:
System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result;
When I create an issue I use:
var response = await httpClient.PostAsync(httpClient.BaseAddress, content);
So the first parameter wants the url you want to send the content to. "issue" is not an url.
My code looks like this. Maybe you can use it.
public async Task<bool> PostIssueAsync(string userpass, string data)
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(Constants.JiraUrl + "rest/api/latest/issue");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", userpass);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(data, Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
try
{
var response = await httpClient.PostAsync(httpClient.BaseAddress, content);
return response.IsSuccessStatusCode;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}

HttpClient - "Unsupported Media Type"

I'm a trying to post the following request but I am getting a "Unsupported Media Type" response. I am setting the Content-Type to application/json. Any help would be appreciated.
var json = JsonConvert.SerializeObject(request);
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
MyResult result = new MyResult();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64ApiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.PostAsync(method, stringContent);
if (Res.IsSuccessStatusCode)
{
var response = Res.Content.ReadAsStringAsync().Result;
result = JsonConvert.DeserializeObject<MyResult>(response);
}
}
After inspecting the raw data sent from my code, I saw that this line was adding the charset:
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
The actual data sent looked like this:
Content-Type: application/json; charset=utf-8
I needed to remove the charset from the request with:
stringContent.Headers.ContentType.CharSet = string.Empty;

Categories