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;
Related
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.
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);
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;
}
}
Could someone please help me convert this ASP .Net Core example (to be used in my Web Api to consume a management API from Auth0) which uses RestSharp into one using HttpClient?
var client = new RestClient("https://YOUR_AUTH0_DOMAIN/oauth/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"grant_type\":\"client_credentials\",\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
I've been struggling... I've got this:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://YOUR_AUTH0_DOMAIN/oauth/token");
but I'm not sure about the rest... thank you
You need to take the request body and create content to post
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://YOUR_AUTH0_DOMAIN/oauth/token");
var json = "{\"grant_type\":\"client_credentials\",\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\"}"
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("", content);
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();