StatusCode 401 Reason Unauthorized when calling PostAsync WebRequest - c#

I am new to the C# HttpClient class and I hope you guys & gals can help me out with my problem. I am getting the StatusCode 401 when trying to call the PostAsync Method. Here's my Code
public WebClient(HttpClient httpClient)
{
string webHost = ConfigurationManager.AppSettings["webHost"];
string webApiKey = ConfigurationManager.AppSettings["webApikey"];
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri(webHost);
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("x-coupa-api-key", "=" + ConfigurationManager.AppSettings["coupaApikey"]);
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
}
public Tuple<bool, Task<HttpResponseMessage>> Comment(comment comment)
{
try
{
string commentUrl = string.Format("{0}api/comments/", _webHost);
var responseMessage = _httpClient.PostAsync(commentUrl, CreateHttpContent(comment));
Log.Error("Response message: " + responseMessage.Result);
return new Tuple<bool, Task<HttpResponseMessage>>(responseMessage.Result.IsSuccessStatusCode, responseMessage);
}
catch (Exception ex)
{
Log.Error("Call to Web failed.", ex);
throw;
}
}
private static HttpContent CreateHttpContent(comment data)
{
var format = "application/xml";
return new StringContent(Common.SerializeUtf8(data), Encoding.UTF8, format);
}
So I am sending an xml with a POST to a webhost - and i get the following Result from PostAsync:
Response message:
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Status: 401 Unauthorized
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-Id: 53e17930-f9fe-4ec4-ae5b-b772ce5f308e
X-Runtime: 0.025822
Cache-Control: no-cache
Date: Wed, 26 Apr 2017 06:07:39 GMT
Content-Type: text/html
}

Found the solution. Shouldn't have used the Authorization, just "add header":
_httpClient.DefaultRequestHeaders.Add("x-coupa-api-key", ConfigurationManager.AppSettings["webApikey"]);

Related

StatusCode: 404, Response when calling the Web API

I have a Web API which uploads the File content to the server.
[HttpPost]
[Route("SaveFileContent")]
public async Task<FileResponse> SaveFileContent([FromForm] SaveFileContentRequest request)
{
return await _service.SaveFile(request);
}
This is my call to the API:
public async Task<FileResponse> SaveFileContent(SaveFileContentRequest request)
{
try
{
var uri = "https://www.mycompanyurl.com";
using (var client = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (var fileContent = new ByteArrayContent(request.File))
{
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent, "file", request.FileName);
form.Add(new StringContent(request.MemberId), "MemberId);
form.Add(new StringContent(request.Country), "Country);
client.BaseAddress = new Uri(uri);
HttpResponseMessage response = await client.PostAsync("/api/Document/SaveFileContent", form);
FileResponse result = JsonConvert.DeserializeObject<FileResponse>(response.Content.ReadAsStringAsync().Result);
return result;
}
}
}
}
}
I get this response at PostAsync():
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Sun, 21 Apr 2013 12:00:03 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 165
Content-Type: application/json; charset=utf-8
}}
When I try to run the API in my local - and use the localhost uri -
var uri = "http://localhost:51515";
It is working fine and getting the 200 OK response.
try to use the full route
[Route("~/api/Document/SaveFileContent")]
public async Task<FileResponse> SaveFileContent([FromForm] SaveFileContentRequest request)

Result from response.Content.ReadAsStringAsync() is empty string (Windows.Web.Http). How do I get response?

When I run this from a browser manually, it returns a response, that looks like this:
{"value":[{"ID":4}]}
Now, I am POSTing it from a Windows IoT Device, using the following code:
private async Task SendPostRequest(string username, string password, Dictionary<string, string> parameters)
{
try
{
// using Windows.Web.Http
HttpFormUrlEncodedContent formattedData = new HttpFormUrlEncodedContent(parameters);
using (HttpBaseProtocolFilter clientHandler = new HttpBaseProtocolFilter())
{
clientHandler.ServerCredential = GetCredentials(username, password);
using (HttpClient httpClient = new HttpClient(clientHandler))
{
//txtCommand.Text = "PostAsync";
HttpResponseMessage response = await httpClient.PostAsync(postUrl, formattedData);
txtResponse.Text = response.ToString();
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
txtResponse.Text += " responseString: " + responseString;
}
}
The result in responseString is an empty string.
The result of response.ToString() looks like this:
StatusCode: 200, ReasonPhrase: 'OK', Version: 2, Content: Windows.Web.Http.HttpStreamContent, Headers:
{
Persistent-Auth: true
Server: Microsoft-IIS/10.0
Transfer-Encoding: chunked
Date: Fri, 27 Aug 2021 15:16:38 GMT
X-Powered-By: ASP.NET
dbgate-version: 1.0
}{
Content-Type: text/plain
}

HttpClient POST to Web API returns 400 Bad Request

I am trying to post captured image from WPF to WebApi method using HttpClient but i am getting 400 BAD REQUEST error.
I have tried in google but unable to resolve the issue. does anyone help me.
Below is the code in WPF
private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
string FileName =
System.IO.Path.GetFullPath("../../captured_images") +
"//captured_image" + DateTime.Now.Day.ToString() +
DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() +
DateTime.Now.Second.ToString() + ".jpg";
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)image.Source));
using (FileStream stream = new FileStream(FileName,
FileMode.Create))
encoder.Save(stream);
string CASAAuthResponse = await
CASSecurity.GetAuthenticationToken();
CASAuthTokenResponse techSeeTokenResponse =
JsonConvert.DeserializeObject<CASAuthTokenResponse>
(CASAAuthResponse);
HttpContent fileStreamContent = new StreamContent(File.OpenRead(FileName));
using (var client1 = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
client1.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
formData.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
formData.Add(fileStreamContent, "face",
Path.GetFileName(FileName));
var response = await
client1.PostAsync(CASIdentifyFaceUrl, formData);
if (!response.IsSuccessStatusCode)
{
return null;
}
}
}
Server Web api:
[HttpPost]
[Route("identify")]
public async Task<IActionResult> Identify(IFormFile face)
{
Guid temporaryUsername = Guid.Empty;
using (var faceStream = face.OpenReadStream())
{
temporaryUsername = await verifyBusiness.IdentifyUser(faceStream,
new Guid(Requester.ClientId));
}
return Ok(temporaryUsername);
}
And i am getting error as descibed below:{StatusCode: 400,
ReasonPhrase: 'Bad Request', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Transfer-Encoding: chunked
Strict-Transport-Security: max-age=2592000 Date: Thu, 20 Jun 2019
11:13:28 GMT Set-Cookie:
ARRAffinity=4cbc3e777eee0146fcbb9f695794b29417cc953731f6f8f581457a1d7cd7aa14;Path=/;HttpOnly;Domain=cas-qa.tempdata.net
Server: Kestrel X-Powered-By: ASP.NET Content-Type:
application/json; charset=utf-8 }}

How to fixed 400 Bad Request of my web API Call in my window service app

I made an auto scheduler where data is forwarded to my AWS Server.
I created a Window Service that runs every min to forward the new data.
I have an existing API that received the data in AWS Server.
Window Service works fine with API on network server
API Address1 : http:\\192.168.0.1\api\data\getdata (Working in network 100%)
API Address2 : https:\\api.mydomain.com\api\data\getdata (Tested in winform and postman
working 100%)
But encountered a problem when window services send data to API Address 2
Here is the code
public static void SendData()
{
var PostData = new Profile
{
ID = 99,
Code = "123",
Email = 'xyz#yahoo.com'
};
try
{
var PostBody = JsonConvert.SerializeObject(PostData);
var PostContent = new StringContent(PostBody, Encoding.UTF8, "application/json");
//BaseAddress = "https:\\api.mydomain.com";
using (var Client = API_Client.GetClient("api/data/getdata"))
{
var Sending = Client.PostAsync(Client.BaseAddress.ToString(), PostContent);
Sending.Wait();
var Response = Sending.Result;
if (Response.IsSuccessStatusCode)
{
Logger.WriteLine("Sending Info to API '" + PostData.ID.ToString() + "'", "Success");
}
else
{
Logger.WriteLine("Sending Info to API '" + PostData.ID.ToString() + "'", Response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
Logger.WriteLine("Error '" + PostData.ID.ToString() + "' To Server", ex.Message);
}
}
Here is Error Message
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
Connection: close
Cache-Control: no-cache
Date: Thu, 13 Dec 2018 06:40:34 GMT
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 41
Content-Type: application/json; charset=utf-8
Expires: -1
}}
API Client Helper
public class API_Client
{
protected static string API_BASE_ADDRESS = "https:\\api.mydomain.com\";
public static HttpClient GetClient(string URL_Target)
{
var Client = new HttpClient()
{
BaseAddress = new Uri(API_BASE_ADDRESS + URL_Target),
Timeout = new TimeSpan(0, 0, 90)
};
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Client.DefaultRequestHeaders.ConnectionClose = true;
return Client;
}
}
Postman

OneNote API Create Notebook

I'm getting a "Bad Request" when I try to create a new OneNote API Notebook.
private async Task<string> CreateSimpleNotebook(string notebookName, string apiRoute)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
catch (Exception ex)
{
string tempEx = ex.ToString();
}
var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute )
{
Content = new StringContent("{ name : '" + WebUtility.UrlEncode(notebookName) + "' }", Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(createMessage);
return response.Headers.Location.ToString();
}
And I call the method with the following:
string url = "https://graph.microsoft.com/v1.0/me/onenote/notebooks/";
// string url = "https://www.onenote.com/api/v1.0/me/notes/notebooks/";
string tempResponse = await CreateSimpleNotebook("EMRTest2", url);
Here is the response:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
client-request-id: acacd4f5-8738-4c46-8150-17aa23413eb5
request-id: acacd4f5-8738-4c46-8150-17aa23413eb5
Transfer-Encoding: chunked
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"South Central US","Slice":"SliceB","Ring":"NA","ScaleUnit":"002","Host":"AGSFE_IN_10","ADSiteName":"SAN"}}
Duration: 772.4124
Cache-Control: private
Date: Sun, 19 Nov 2017 20:59:10 GMT
Content-Type: application/json
}}
You should use Content-Type JSON
The name of the property you are looking for is not "name", it is "displayName"
Additionally, crafting JSON by appending string is not best practice - I recommend using a JSON library, like NewtonSoft JSON.NET.

Categories

Resources