Get string returned from a PostAsync event - asp.net-mvc-4

I'm using HttpClient like this in my console app:
using (var http = new HttpClient(handler))
{
http.BaseAddress = new Uri("http://127.0.0.1:34323/");
var response = await http.PostAsync("/api/generate", new StringContent(
JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"));
Console.WriteLine(response.Content.ToString());
}
In debug mode, I can see that the controller is returning a string of JSON.
However, I only get this written to the console:
System.Net.Http.StreamContent
How can I get it to write the actual JSON that's being returned?
Thanks!

Try below line:
Console.WriteLine(response.Content.ReadAsStringAsync().Result.ToString());

Related

'Restclient' does not contain a 'BaseUrl' Error

I am working on Asp.net core project. trying to send mail using mailgun. used mailgun C# code given in https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api
But getting an error "RestClient" does not contain a "BaseUrl" error.
I saw your Comment Code, I think You have to Change this to get the Output.
var client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v3";
client.Authenticator = new HttpBasicAuthenticator("api", "YOUR_API_KEY");
var request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "address#domain.com");
//Change Resource and AddParameter as per need
var response = client.Execute(request);
dynamic content = Json.Decode(response.Content);
var client = new RestClient(new Uri("yourbaseurl"));

Get image by client request in Blazor

I try to get a Base64 from a image-URL in my hosted Blazor Webassambly. The URL contains a link to a picture.
using (var client = new HttpClient())
{
var bytes = await client.GetByteArrayAsync(url); // there are other methods if you want to get involved with stream processing etc
var base64String = Convert.ToBase64String(bytes);
return base64String;
}
Throws Exception:
TypeError: Failed to fetch
The Exception is thrown with any client method.
var result = await client.[X](url);
Why its impossible to make a request with he http client?
I would try it with first retrieving the link to the picture and then downloading the bytes from there.
string pictureLink = await client.GetStringAsync(url);
var base64String = Convert.ToBase64String(await client.GetByteArrayAsync(pictureLink));

net Core 3.1 Object null in WebApi method after PostAsJsonAsync

Im using this line to consume the API post method
var postTask = client.PostAsJsonAsync("AgregarNegocio", new StringContent(JsonConvert.SerializeObject(model).ToString(), Encoding.UTF8, "application/json"));
however when the API method is hit
public IActionResult AgregarNegocio([FromBody]NegocioViewModel model)
all the properties in model are null...
i already tried with and without [FromBody] and other solutions but none has worked yet, any suggestions?, thanks!
You need to construct your http client like this:
_client = new HttpClient { BaseAddress = new Uri("your http://my base url goes here"),
Timeout = new TimeSpan(0, 0, 0, 0, -1) };
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));//add json header
//_client.DefaultRequestHeaders.Add("Bearer", "some token goes here");
and you need to call your method like this:
var postTask = await _client.PostAsJsonAsync("AgregarNegocio", model);
make sure you call "await" on it because it is async.
NOTES:
Notice that I added MediaTypeWithQualityHeaderValue to indicate that it is json.
Also using Route usually is not a good idea... It is better to use HttPost("MyRoute") because it combined the ControllerName + Route. But it is up to you.
Try to use PostAsync instead of PostAsJsonAsync
var postTask = await client.PostAsync("AgregarNegocio", new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"));
You can use the HttpClient extension method :
https://learn.microsoft.com/en-us/previous-versions/aspnet/hh944682(v=vs.118)
PostAsJsonAsync(
this HttpClient client,
string requestUri,
T value
)
var postTask = client.PostAsJsonAsync<NegocioViewModel>("AgregarNegocio", model);
You can use PostAsync but also do not forget about using HttpClient in right way as i described in this article.

PDF generation in mvc4 with itextsharp

I am working on pdf generation, it is successfully implemented using itextsharp.dll. It’s working fine on local environment after publish also. We have our own server at other site
But same code doesn't work on the server,pdf is not generated instead it gives an error: 'The document has no pages.'
Initially I thought it is due to no data in document but it works locally with or without data in the document.
I had code implemented as follows to make a web request Is any problem in that ??
try
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strPdfData + "?objpatId=" + patID);
var response = myHttpWebRequest.GetResponse();
myHttpWebRequest.Timeout = 900000;
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
content = sr.ReadToEnd();
}
create a method in the controller:
[HttpGet]
public JsonResult GetFile()
{
var json = new WebClient().DownloadFile(string address, string fileName);
//This code is just to convert the file to json you can keep it in file format and send to the view
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var oc = Newtonsoft.Json.JsonConvert.DeserializeObject<countdata[]>(Convert.ToString(result.countdata));
return Json(oc, JsonRequestBehavior.AllowGet);
}
In the view just call this function:
#Url.Action('genPDF','GetFile');

Issues performing a query to Solr via HttpClient using Solr 3.5 and HttpClient 4.2

I am trying to query my local Solr server using HttpClient and I cannot figure out why the parameters are not being added to the GET call.
My code for doing this is:
HttpRequestBase request = new HttpGet("http://localhost:8080/solr/select");
HttpParams params = new BasicHttpParams();
params.setParameter("q", query);
params.setParameter("start", String.valueOf(start));
params.setParameter("rows", String.valueOf(rows));
request.setParams(params);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
return stringToStreamConversion(is); //500 error, NullPointerException, response is empty
I have tried to return several things in hopes of seeing what I would get and trying to figure out where the problem was. I have finally realized that I was only getting back the http://localhost:8080/solr/select when I returned
return request.getURI().toURL().toString();
I cannot figure out why the parameters are not getting added. If I do
return request.getQuery();
I get nothing back...any ideas? Thanks for the help in advance!
From what I have seen you are not able to associate your paeans with the request.
So, instead of creating a new HttpParams object and associating it with request, can you try the following approach ?
httpCclient.getParams().setParameter("q", query");
....
The simpler option is to use the approach I used in HTTPPostScheduler, like this:
URL url = new URL(completeUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("type", "submit");
conn.setDoOutput(true);
// Send HTTP POST
conn.connect();