net Core 3.1 Object null in WebApi method after PostAsJsonAsync - asp.net-core

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.

Related

Get string returned from a PostAsync event

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

Convert IRestResponse to IRestResponse<T>

I have executed RestRequest and got non-typed IRestResponse.
How can I convert it to IRestResponse<T>?
For example IRestResponse<MyErrorData> or IRestResponse<MyData>?
You need to use the generic overload of Execute:
var client = new RestClient();
client.BaseUrl = BaseUrl;
request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
var response = client.Execute<T>(request);
Execute<T> is the key to getting back a typed response.
I found that, depending on the version of RestSharp you have installed, Execute<T> threw a compiler error. (Tho it seems fine in v106.15.)
Another option is to cast it, which seems to work when the first option doesn't:
RestClient client = new RestClient();
IRestResponse<T> response = (IRestResponse<T>)client.Execute(request);
Also, don't forget that your method (or class) must be decorated with the T type parameter:
Eg
partial void InterceptResponse<T>(IRestRequest request, ref IRestResponse<T> response)
...
RestClient client = new RestClient();
IRestResponse<T> response = client.Execute<T>(request);
(or IRestResponse<T> response = (IRestResponse<T>)client.Execute(request);)
....
(In this example, I'm intercepting a RestResponse, doing something, such as re-calling, and passing back the new response as ref response.)

Sending Commands from an MVC4 site to Another

I have two sites: one of them controls the other sending some commands through Web API. The idea is: the action of the controller site sends a command to the other site, gets the response and perform some business rules, without redirecting to the other site.
I have tons of examples explaining how to implement this via jQuery, but I want to make the controller post the data to the other site, instead of the view.
I found an approach at this answer: How to use System.Net.HttpClient to post a complex type?, but I want the answer for an JSON approach.
Can someone post a simple example using JSON showing how to do this?
As I didn't find a brief answer to my question, I'll post the solution I've made.
As the method uses an HttpClient method that requires async statements, the action below was implemented retuning a Task<ActionResult>. Another modification is if you're saving an object in context.
Instead of using:
context.SaveChanges();
You'll have to use:
await context.SaveChangesAsync();
The code below implements an Action from an ASP.NET MVC4 Controller:
[HttpPost]
public async Task<ActionResult> Create(MyModel model)
{
if (ModelState.IsValid)
{
// Logic to save the model.
// I usually reload saved data using something kind of the statement below:
var inserted = context.MyModels
.AsNoTracking()
.Where(m => m.SomeCondition == someVariable)
.SingleOrDefault();
// Send Command.
// APIMyModel is a simple class with public properties.
var apiModel = new APIMyModel();
apiModel.AProperty = inserted.AProperty;
apiModel.AnotherProperty = inserted.AnotherProperty;
DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(APIMyModel));
// use the serializer to write the object to a MemoryStream
MemoryStream ms = new MemoryStream();
jsonSer.WriteObject(ms, apiModel);
ms.Position = 0;
//use a Stream reader to construct the StringContent (Json)
StreamReader sr = new StreamReader(ms);
// Note if the JSON is simple enough you could ignore the 5 lines above that do the serialization and construct it yourself
// then pass it as the first argument to the StringContent constructor
StringContent theContent = new StringContent(sr.ReadToEnd(), System.Text.Encoding.UTF8, "application/json");
HttpClient aClient = new HttpClient();
Uri theUri = new Uri("http://yoursite/api/TheAPIAction");
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
if (aResponse.IsSuccessStatusCode)
{
// Success Logic. Yay!
}
else
{
// show the response status code
String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " - Reason: " + aResponse.ReasonPhrase;
}
return RedirectToAction("Index");
}
// if Model is not valid, you can put your logic to reload ViewBag properties here.
}

YouTube API v3.0 VideoReponse and ListRequest class

Using the first example, found here https://developers.google.com/youtube/v3/code_samples/dotnet
for the .Net YouTube 3.0 API, I'm doing something very similar but using a VideoResource object not a SearchResource. Code from the example:
YoutubeService youtube = new YoutubeService(new BaseClientService.Initializer() {
ApiKey = credentials.ApiKey
});
SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
listRequest.Q = CommandLine.RequestUserInput<string>("Search term: ");
listRequest.Order = SearchResource.Order.Relevance;
SearchListResponse searchResponse = listRequest.Fetch();
Notice after setting the fields on the ListRequest object a Fetch() method is called to initialize a SearchListResponse object. However, this Fetch() method does not appear to be part of the API! What gives? Does anyone know how to execute the listrequest so that it returns a ListReponse object?
Instead using listRequest.Fetch(); try to use listRequest.Execute();

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