Upload File and Convert to Base64 (406 Error Not Acceptable ) - c#

What I am trying to do here is that I am going to send a converted pdf to base64 to an endpoint where in this is the endpoint
HTTP-HEADERS:
api-key: your-key
Content-Type: application/json
Request Body JSON
{
"file":
{
"mime": "application/pdf",
"data": "base64-data="
}
}
and here's how I Upload and Convert the my file
public async Task UploadFile()
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; //user canceled selecting image
string fileName = fileData.FileName;
string contents = Encoding.UTF8.GetString(fileData.DataArray);
var stream = fileData.GetStream();
var bytes = new byte[stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
string base64 = Convert.ToBase64String(bytes);
File ru = new File();
ru.mime = "application/pdf";
ru.data = "base64-data="+base64;
string url = "ENDPOINT URL";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders
.Accept
.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string jsonData = JsonConvert.SerializeObject(ru);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
requestMessage.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("api-key", "API KEY HERE");
requestMessage.Headers.Add("Accept-Encoding", "gzip");
HttpResponseMessage response = await client.SendAsync(requestMessage);
string result = await response.Content.ReadAsStringAsync();
if(result!= null)
{
resultLabel = result;
}
now it gives me the error
{"Message":"HTTP 406 Not Acceptable. There was an error with your request. Please check your payload and then try again,","Result":406}

By following the suggestion of #Jason in the comment section I have solved my problem
https://learning.postman.com/docs/sending-requests/generate-code-snippets/
Hope this solves someone having thesame problem as mine.

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.

Microsoft graph email attachment status code 405. Method not allowed

I'm getting Status Code 405, Method not allowed error when sending email that has an attachment. I'm using HttpClient to post my request to the API rather Microsoft Graph Client. Don't want to have dependency of Microsoft Graph library. My send email without attachment works fine but not with the attachment.
try
{
const string url = "https://graph.microsoft.com/v1.0/users/myemail#outlook.com/sendMail";
var path = "C:\\Attachments\\image1.jpg";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
byte[] bytes = File.ReadAllBytes(path);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
var email = new Email
{
Message = new Message
{
Subject = "Test subject",
Body = new Body
{
ContentType = "Text",
Content = "message"
},
ToRecipients = new List<Recipients>
{
new Recipients
{
EmailAddress = new EmailAddress
{
Address = "testemail#outlook.com"
}
}
},
Attachments = new List<Attachment>
{
new Attachment
{
Name = "image1.jpg",
ContentBytes = base64String,
ContentType = "image/jpeg"
}
}
}
};
var jsonMessage = JsonConvert.SerializeObject(email);
var content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
}
}
catch (HttpRequestException e)
{
Console.WriteLine(e.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Following is the answer if someone else get stuck with same issue
For "Attachment" object, Microsoft Graph need '#odata.type' property with the value of '#microsoft.graph.fileAttachment'
Attachments = new List<Attachment>
{
new Attachment
{
//GraphDataType property name will be changed to #odata.type
GraphDataType = "#microsoft.graph.fileAttachment",
Name = "image1.jpg",
ContentBytes = base64String,
ContentType = "image/jpeg"
}
}
Replace 'GraphDataType' inside Serialized Object with '#odata.type'
var jsonMessage = JsonConvert.SerializeObject(email);
jsonMessage = jsonMessage.Replace("GraphDataType", "#odata.type");

ReasonPhrase Not Acceptable HTTPClient C#

I am trying to send a json object with a base4 encoded file to a web api service using the code below
MemoryStream target = new MemoryStream();
q.fileUpload.InputStream.CopyTo(target); //q.fileUpload is an HttpPostedFilebase pdf
var myfile= Convert.ToBase64String(target.ToArray());
var requestbody = new {
filedata = new
{
mimetype = "application/pdf",
basedata = "base64-data=" + myfile
}
};
var jsondata = JsonConvert.SerializeObject(requestbody );
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://web.base.url/");
client.DefaultRequestHeaders.Add("X-API-KEY", "SOMEAPIKEY");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "upload");
request.Content = new StringContent(jsondata, Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var responsetask= client.SendAsync(request);
return Json(responsetask);
But i everytime i call this i get a 406 Not Acceptable response. Anyone knows what causes it?

400 Bad Request C# Microsoft Face Api

I am trying to get simple functionality from the Microsoft Face API, using this example provided (link):
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request parameters
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
queryString["returnFaceAttributes"] = "{string}";
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{body}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("< your content type, i.e. application/json >");
response = await client.PostAsync(uri, content);
}
Whenever I execute the code, I get a 400 bad request, of which I cannot how to view the specific cause. This is how mine looks:
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "xxxxxxxxxxxxxxxxxxxxxxx");
// Request parameters
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
queryString["returnFaceAttributes"] = "Age";
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{ \"url\":\"http://i0.kym-cdn.com/photos/images/newsfeed/000/272/907/dc1.jpg/ \"}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
Console.Write(response.StatusCode);
}
The code looks fine and the only issue I see is that your image is not accessible. I am getting access denied error, if I try to access the image directly via browser. Is that something you have checked?
I tried the below code and it works fine:
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key","please use your key");
// Request parameters
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
queryString["returnFaceAttributes"] = "age";
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{ \"url\":\"https://lh5.googleusercontent.com/-AI__M0nZDU4/AAAAAAAAAAI/AAAAAAAAAGs/P5tdI3rFaFs/s0-c-k-no-ns/photo.jpg \"}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
Console.Write(response.StatusCode);
}

A method was called at an unexpected time in HttpClient MultipartFormDataContent

I have to post the multipart data to the server but I am getting below error
I am using the below code
public async static Task<string> HttpImagePostMethod(byte[] wInputData, string Uri, string path)
{
string result = string.Empty;
try
{
#region For Https (Secure) Api having SSL
var filter = new HttpBaseProtocolFilter();
filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
var client = new System.Net.Http.HttpClient(new WinRtHttpClientHandler(filter));
#endregion
MultipartFormDataContent requestContent = new MultipartFormDataContent();
// StreamContent content = new StreamContent(wInputData);
var content = new ByteArrayContent(wInputData);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
requestContent.Add(content, "file", path);
requestContent.Headers.Add("X-API-Key", UrlFactory.X_API_Key_Value);
requestContent.Add(new StringContent("144"), "type");
HttpResponseMessage aResp = await client.PostAsync(UrlFactory.BaseUrl + Uri, requestContent);
if (aResp.IsSuccessStatusCode)
{
result = await aResp.Content.ReadAsStringAsync();
}
else
{
result = await aResp.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
result = string.Empty;
}
return result;
}
I am getting error at this line
HttpResponseMessage aResp = await client.PostAsync(UrlFactory.BaseUrl + Uri, requestContent);
Due to this line
requestContent.Headers.Add("X-API-Key", UrlFactory.X_API_Key_Value);
Myself Answer this question maybe helpful to my other friends...
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new System.Uri(UrlFactory.BaseUrl + Uri);
httpRequest.Content = requestContent;
httpRequest.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
httpRequest.Headers.TryAddWithoutValidation("X-API-Key", UrlFactory.X_API_Key_Value);
Client(HttpClient) shouldn't contain any header, we declaring header in HttpRequestMessage
As the error message says, you're trying to set a header on the content but it doesn't belong there; your API token is a property of the request itself and not of its content.
Try adding that header to client.DefaultRequestHeaders instead.

Categories