I am with a problem. I have 2 WebApi´s . The webapi2 get the data from DB and return the IMAGE. Here, its ok and working. If i try on browser, show me the image or if i change, the byte array.
The problem is with the Webapi1 that calls this webapi2. I always receive the HttpResponseMessage with false for IsSuccessStatusCode. The error is 500 internal server error.
I am a newbie and i don´t know what to do...i already tryed a lot of things
public async Task<HttpResponseMessage> GetFoto(string exemplo, string exemple2)
{
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
};
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://192.111.56.1:1762/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/Tr/Test?exemplo="+exemplo+"&pk="+pk+"");
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsByteArrayAsync().Result;
var stream = new MemoryStream(data);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
return null;
}
}
}
My webapi that Works and return me a Image:
//connections code that doesn´t matter....
try
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(imgBytes);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
The error is because when you pass a value on the browser, they change some carachters... So, you are passing 2 values... you have to use
On the webapi 1
var MIRACLE = Uri.EscapeDataString(exemplo);
And at the webapi2
var MIRACLE2 = Uri.UnescapeDataString(MIRACLE)
As per your code, the web api 1 will accept only the media type = "application/json".
This is because you have added the below code :
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
So either you remove the line of code or change it to "image/jpeg" from "application/json".
Related
I keep getting this error when trying to use POST Method.
I need to get from the API a list of certificates into a LIST, I know that "lista" is null right now, since I can´t get the API to bring me the lists yet.
public async Task<List<Certificaciones>> grillaCertificadosAsync(int id)
{
List<Certificaciones> lista = new List<Certificaciones>();
var cert = new jsonCert()
{
idProyecto = id
};
var id1 = JsonConvert.SerializeObject(cert);
var content = new StringContent(id1, Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.PostAsync("https://certificacionesbuho.mendoza.gov.ar/api/BuhoBlanco/GetInfoCert", content);
var responseBody = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
return lista;
This is the API.
[Route("Api/BuhoBlanco/GetInfoCert")]
[System.Web.Http.ActionName("GetInfoCert")]
[System.Web.Http.HttpPost]
public Respuesta GetInfoCert([FromBody]infoCertRequest infoCert)
{
Respuesta rta = new Respuesta();
try
{
BuhoServicio.ServicioBuhoBlanco _servicio = new BuhoServicio.ServicioBuhoBlanco();
rta.Exito = true;
rta.StatusCode = HttpStatusCode.OK;
rta.Data = _servicio.infoCertificados(infoCert.idProyecto);
//((IDisposable)_servicio).Dispose();
return rta;
}
catch (Exception ex)
{
rta.Error = ex.Message;
rta.Exito = false;
rta.StatusCode = HttpStatusCode.InternalServerError;
return rta;
}
}
IMHO route should be like this
[HttpPost("~/Api/BuhoBlanco/GetInfoCert")]
public Respuesta GetInfoCert([FromBody]infoCertRequest infoCert)
I am trying to call an api(POST method) with HttpClient.PostAsJsonAsync. However, it stopped at httpClient.PostAsJsonAsync without any exception.
The source code as below:
public static async Task<oResult> PostApi(string JSON_sObject, string sEnd_Url) {
oResult oResult = new oResult();
var Data = JsonConvert.DeserializeObject(JSON_sObject);
var Url = "http://localhost:44340/" + sEnd_Url;
HttpClient httpClient = new HttpClient();
try {
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data); // it stopped here
if (response.IsSuccessStatusCode)
{
var sResponse_content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<oResult>(sResponse_content);
}
else
{
return oResult;
}
}
catch (Exception ex)
{
LogFile(ex);
return oResult;
}
}
Please advice me if any issue from the source code.
Thank you
you should not trying serialize deserialize twice
remove from your code
var Data = JsonConvert.DeserializeObject(JSON_sObject);
and replace
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data);
with this
var content = new StringContent(JSON_sObject, Encoding.UTF8, "application/json");
var response = await client.PostAsync(sEnd_Url, content);
also fix base httpclient address
var baseUri= #"http://localhost:44340";
using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };
try {
I Have an API that takes an IFormFile and returns an IActionsresult with some values. When i call the API with postman it works fine I get a nice 200 Ok response with the data I am looking for. But when I trie to call the API from within another program I get nothing in response. I get no errors, it's just that the program seems to wait for a response that never shows. I am simply wondering if anyone can see the problem with this code any help would be greately apriciated.
Both my API and my program is on the same computer and here is the code i use to call the API.
public static async Task<string> Calculate()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var content = new MultipartFormDataContent())
{
var img = Image.FromFile("path");
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.jpeg);
content.Add(new StreamContent(new MemoryStream(ms.ToArray())), "image", "myImage.jpg");
using (var response = await client.PostAsync($"http://localhost:####/api/1.0/###", content))
{
var responseAsString = await response.Content.ReadAsStringAsync();
return responseAsString;
}
}
}
}
Successful request using postman:
Post Request using Postman
Try this-
using (var client = new HttpClient())
{
client.BaseAddress = new Uri($"http://localhost/###");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var content = new MultipartFormDataContent())
{
content.Add(new StreamContent(new MemoryStream(image)), "image", "myImage.jpg");
using (var response = await client.PostAsync($"http://localhost:#####/###/###/###", content).ConfigureAwait(false))
{
if (response.StatusCode == HttpStatusCode.OK)
{
var responseAsString = response.Content.ReadAsStringAsync().Result;
var receiptFromApi = JsonConvert.DeserializeObject<Receipt>(responseAsString);
var metadata = new metadata(bilaga)
{
Value1 = fromApi.Value1.Value,
Value2 = fromApi.Value2.Value,
Value3 = fromApi.Value3.Value,
Value4 = fromApi.Value4.Value
};
return metadata;
}
else
{
throw new InvalidProgramException();
}
}
}
}
reference- https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
I'm trying to Upload Track to sound cloud. So far i'm successfully able to get auth token but when i tried to 'PostAsync' it throws exception
A Task was canceled. I have also set the timeout value but still the same error. Issue seems to be something wrong with what i'm doing. Below is the code which i'm using and i have taken it from stack overflow but with no luck.
private async Task<bool> StartUploadAsync(PubVidoInfo pubStuff)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.ConnectionClose = true;
httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Mixcraft", "1.0"));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
ByteArrayContent titleContent = new ByteArrayContent(Encoding.UTF8.GetBytes(pubStuff.title));
ByteArrayContent descriptionContent = new ByteArrayContent(Encoding.UTF8.GetBytes(pubStuff.description));
ByteArrayContent sharingContent = null;
if (pubStuff.publishedFileState == PubFileState.PF_Public)
{
sharingContent = new ByteArrayContent(Encoding.UTF8.GetBytes("public"));
}
else
{
sharingContent = new ByteArrayContent(Encoding.UTF8.GetBytes("private"));
}
ByteArrayContent byteArrayContent = new ByteArrayContent(File.ReadAllBytes(pubStuff.pubFilePath));
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(titleContent, "track[title]");
content.Add(descriptionContent, "track[description]");
content.Add(sharingContent, "track[sharing]");
content.Add(byteArrayContent, "track[asset_data]", Path.GetFileName(pubStuff.pubFilePath));
try
{
HttpResponseMessage message = await httpClient.PostAsync(new Uri("https://api.soundcloud.com/tracks"), content);
if (message.IsSuccessStatusCode)
{
PubUploadStatus = PubUploadStatus.US_Finished;
}
else
{
PubUploadStatus = PubUploadStatus.US_Failed;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
PubUploadStatus = PubUploadStatus.US_Failed;
}
return true;
}
Is there any thing i'm doing ? Can any one point out the issue in particular code.
Regards,
I'm using this code to POST XML to a REST webservice, but am just getting a vague '500 Server Error'. If I paste the same XML into Fiddler it works perfectly, so what am I doing wrong?
using (var client = new HttpClient())
{
var httpContent = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
var response = client.PostAsync(new Uri("httpsapiurl"),httpContent).Result;
if (response.IsSuccessStatusCode)
{
// EDITED: this isn't hit as IsSuccessStatusCode is always false
//Stream stream = await response.Content.ReadAsStreamAsync();
}
}
Could it be that you need to set the Content type on the request?
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, URL);
req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
await httpClient.SendAsync(req).ContinueWith(async respTask =>
{
Debug.WriteLine(req.Content.ReadAsStringAsync());
};
}
catch (Exception ex)
{
}
Especially this line is important. I had similar problem with an API that refused to spit anything back when not setting the Content-Type header correct.
req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
Don't know if it can help.