StatusCode: 404, Response when calling the Web API - c#

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)

Related

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
}

Unable to get json data from curl graph api using c#

I'm executing curl graph api using c#.
I took my curl query used this website and convert it into c#.
https://curl.olsh.me/
Api is able to give 200 ok status code and but output is below-
{
"extensions" : {
"requestId" : "123"
},
"data" : null,
"errors" : [ {
"message" : "Unable to process JSON",
"extensions" : {
"errorType" : "developer_error",
"errorClass" : "VALIDATION"
}
} ]
}
result string conv: StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: keep-alive
Braintree-Version: 2016-10-07
Strict-Transport-Security: max-age=31536000; includeSubDomains
Vary: Braintree-Version
X-Cache: Miss from cloudfront
X-Amz-Cf-Pop: MIA3-C2
X-Amz-Cf-Id: 111
Date: Tue, 10 Sep 2019 16:13:54 GMT
Via: 1.1 demo.cloudfront.net (CloudFront)
Content-Length: 286
Content-Type: application/json
}
C# code -
HttpClientHandler handler = new HttpClientHandler()
{
UseProxy = false,
};
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://demo/graphql"))
{
// Prod token
request.Headers.TryAddWithoutValidation("Authorization", "Basic abc");
request.Headers.TryAddWithoutValidation("Braintree-Version", "2019-01-01");
request.Content = new StringContent("{\"query\": \"{ report { transactionLevelFees(date: \"2019-08-28\"){ url } } }\" }", Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.SendAsync(request);
// Get the response content.
HttpContent responseContent = response.Content;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine((await reader.ReadToEndAsync()));
}
Console.WriteLine($"result string conv: {response }");
}
}
I expect in output i should get something in data json

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

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.

Download file prompt when using WebAPI HttpResponseMessage

I have a method in my API that returns a HttpResponseMessage:
[HttpGet, HoodPeekAuthFilter]
public HttpResponseMessage GlobalOverview()
{
try
{
StatsRepo _statsRepo = new StatsRepo();
string file = _statsRepo.IncidentData().AsCSVString();
if (file == null)
{
return Request.CreateResponse(HttpStatusCode.NoContent);
}
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(file);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "GlobalOverview.csv";
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
In my MVC Web Apllication i have a controller Action that needs to call the API and return the file:
[Authorize]
[HttpGet]
public HttpResponseMessage GlobalOverview()
{
HttpResponseMessage file = new HttpResponseMessage();
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(this.UserName + ':' + this.Password)));
Task<HttpResponseMessage> response = httpClient.GetAsync("api.someDomain/Reporting/GlobalOverview");
file = response.Result;
}
return file;
}
If i access the API url directly it prompts me for a username and password, and then the Save File dialogue appears, and i can download the file.
If i navigate to the Action in my Web Application then i get the following response output to screen:
StatusCode: 200,
ReasonPhrase: 'OK',
Version: 1.1,
Content: System.Net.Http.StreamContent,
Headers: { Pragma: no-cache X-SourceFiles: = XXXXXXX
Content-Disposition: attachment;
filename=GlobalOverview.csv
Content-Type: application/octet-stream Expires: -1
I take it i need to return a FileResult, but i have no clue as to how to convert the HttpResponseMessage to a FileResult.
In your MVC controller you can try returning a FileResult, and use the File() method reading the response of your API as byte array.
[Authorize]
[HttpGet]
public FileResult GlobalOverview()
{
HttpResponseMessage file = new HttpResponseMessage();
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(this.UserName + ':' + this.Password)));
Task<HttpResponseMessage> response = httpClient.GetAsync("api.someDomain/Reporting/GlobalOverview");
file = response.Result;
}
return File(file.Content.ReadAsByteArrayAsync().Result, "application/octet-stream", "GlobalOverview.csv");
}

Categories

Resources