0

I have to post the multipart data to the server but I am getting below error

enter image description here

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

thanks Solal, if I set the header like this, it gives error: Value doesnot fall within expected range.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.