400 Bad Request C# Microsoft Face Api - c#

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

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.

Postman form-data: How to program it inside a HttpRequestMessage?

I am doing a request through postman to a specific url but I set the form-data type in order to get data to the site like this:
Now I want to program this request inside C# but everything I tried so far is returning a 400 Bad Request response. This is what I tried:
public async Task<CheckAccessTokenModel> CheckAccessTokenAsync(string accessToken)
{
string uriString = "someurl";
var uri = new Uri(uriString);
try
{
using(var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri
};
var ClientId = ConfigurationAccessor.Configuration["WebCredentials:ClientId"];
var Secret = ConfigurationAccessor.Configuration["WebCredentials:Secret"];
var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{ClientId}:{Secret}"));
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent("token"), accessToken);
request.Content = content;
var response = await httpClient.SendAsync(request);
var checkTokenResponseData = await response.Content.ReadAsStringAsync();
//return new CheckAccessTokenModel { Active = true, Exp = 1647431224233 };
return JsonConvert.DeserializeObject<CheckAccessTokenModel>(checkTokenResponseData);
}
}
catch
{
return null;
}
}
I am doing it with the MultipartFormDataContent Object as suggested by many others here but it still won't work.
What can be the problem here?
EDIT: Wrong picture replaced
You can simply
request.Content = new StringContent($"token={accessToken}");
With form data I think it's something like this:
var data = new Dictionary<string, string>
{
{"token", acccessToken}
};
using var content = new FormUrlEncodedContent(data);
request.Content = content;

Strange behavior in HttpRequestMessage's Content-Type header

I tried to make HTTP POST request with application/json in body to an external web-service from C# (.NET Core 2.2.104).
I've already read all similar questions in SO and wrote this code:
SignXmlRequestDto requestBody = new SignXmlRequestDto(p12, model.SignCertPin, model.Data);
string json = JsonConvert.SerializeObject(requestBody);
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = ncanNodeUrl,
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
},
Content = new StringContent(JsonConvert.SerializeObject(json))
};
var response = await httpClient.SendAsync(httpRequestMessage);
string responseString = await response.Content.ReadAsStringAsync();
I am getting an error from service, it says: "Invalid header Content-Type. Please set Content-Type to application/json". What is interesting here, if I simulate this request from Postman, then everything work well and I get successful response.
Updated: as #Kristóf Tóth suggested, I modified my code to:
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = ncanNodeUrl,
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
var response = await httpClient.SendAsync(httpRequestMessage);
string responseString = await response.Content.ReadAsStringAsync();
but it still gives me the same error message.
Content-Type is a content header. It should be set on the content, not the request itself. This can be done either using the StringContent(string,Encoding,string) constructor :
Content = new StringContent(JsonConvert.SerializeObject(json),Encoding.UTF8, "application/json")
or by setting the StringContent's Headers.ContentType property :
var content=new StringContent(JsonConvert.SerializeObject(json));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
This might be an encoding issue. You should use JsonContent not StringContent OR you can do something similar:
// Serialize into JSON String
var stringPayload = JsonConvert.SerializeObject(payload);
// Wrap JSON StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

How to upload video to Microsoft Video Indexer(mic cognitive service api) through the api call?

How to post video to endpoint of the videoindexer "https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns".
static async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "mykey");
// Request parameters
queryString["name"] = "name";
queryString["privacy"] = "Private";
var uri = "https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns?" + queryString;
HttpResponseMessage response;
// Request body
using (var content = new MultipartFormDataContent())
{
content.Add(new StreamContent(File.Open(#"file", FileMode.Open)), "file", "filename");
try
{
response = await client.PostAsync(uri, content);
Console.WriteLine(response);
}
catch (Exception e)
{
}
}
}
I am getting "A Task was canceled" exception. Please help.
The api works fine when i am using videourl
It was because while trying to upload, my request was getting timed out.
I added
client.Timeout = TimeSpan.FromMinutes(30);
and now it's fixed.

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