I've created a HttpClient instance to invoke an API with post method.
using (var client = new HttpClient())
{
var person = new Stu();
person.ApplicantId = "48751889-D86E-487B-9508-000EAB65F11F";
var json = JsonConvert.SerializeObject(person);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var url = "http://localhost:52085/api/CollegeService/IsCoolegeStudent";
// var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
public class Stu
{
public string ApplicantId { get; set; }
}
When I check my API out , I receive ApplicantId of my object is Null.
I cant not figure out why ApplicantId is Null.
Finally I've changed my [FromForm] to[FromBody] in my API and it worked correctly but it stuck on this line var response = await client.PostAsync(url, data);and doesn't go on.
the await keyboard make my app stuck ,I've changed it this way
var response = await client.PostAsync(url, data).ConfigureAwait(false);
but I didn't figure it out why it cause this problem.
If you using FromForm attribute, you should use FormUrlEncodedContent instead of StringContent as content type when you send POST message. If you still want send json - change FromForm at IsCoolegeStudent method to FromBody.
Related
I am a beginner to GET and POST. I apologize if the question sounds stupid. But I need your help in guiding me to do it the correct way.
I have to periodically do GET from server A indefinitely until user terminate using Ctrl + C
To check at interval I use the timer below
Timer timer = new Timer(RunTask, null, 3000, 3000);
Where RunTask is the callback method consists of GET method to retrieve data below
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(urlA);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<RootObject>(responseBody);
}
Then register the data to server B through POST method
using (HttpClient client = new HttpClient())
{
var json = JsonConvert.SerializeObject(rootIssue);
var output = new StringContent(json, Encoding.UTF8, "application/json");
var result = await client.PostAsync(urlB, output);
string response = result.Content.ReadAsStringAsync().Result;
}
Once registered, server B will return with updated info which I have to POST back to server A
using (HttpClient client = new HttpClient())
{
var json = JsonConvert.SerializeObject(rootIssue);
var output = new StringContent(json, Encoding.UTF8, "application/json");
var result = await client.PostAsync(urlA, output);
string response = result.Content.ReadAsStringAsync().Result;
}
My question here is, what is the best approach for me to do all these queries in my console app? Should I separate each GET and POST to these
GetFromA()
PostToB()
PostToA()
I am concerned if I do it this way, is it possible that PostToB() will POST with incomplete response from GetFromA()?
Or should I combine GET and POST from A to B in one method to something like
GetFromAPostToB()
I hope that someone can point me in the correct direction.
Thanks.
I'm working with ASP.NET MVC (backend being C#) and I'm trying to send a json that would look like this :
{
"store_id": "store3",
"api_token": "yesguy",
"checkout_id": "UniqueNumber",
"txn_total": "10.00",
"environment": "qa",
"action": "preload"
}
to another web site, suppose it's something like:
https://TestGate.paimon.com/chkt/request/request.php
Through some research I found this :
Send json to another server using asp.net core mvc c#
Looks good but I'm not working in core, my project is just normal ASP.NET MVC. I don't know how to use json functions to send it to a web site.
Here is what I tried (updated after inspired by Liad Dadon answer) :
public ActionResult Index(int idInsc)
{
INSC_Inscription insc = GetMainModelInfos(idinsc);
JsonModel jm = new JsonModel();
jm.store_id = "store2";
jm.api_token = "yesguy";
jm.checkout_id = "uniqueId";
jm.txn_total = "123.00";
jm.environment = "qa";
jm.action = "preload";
var jsonObject = JsonConvert.SerializeObject(jm);
var url = "https://gatewayt.whatever.com/chkt/request/request.php";
HttpClient client = new HttpClient();
var content = new StringContent(jsonObject, System.Text.Encoding.UTF8, "application/json");
System.Threading.Tasks.Task<HttpResponseMessage> res = client.PostAsync(url, content);
insc.response = res.Result; // This cause an exeption
return View(insc);
}
When ths Json is posted correctly, the other web site will answer me with is own Json :
{
"response" :
{
"success": "true",
"ticket": "Another_Long_And_Unique_Id_From_The_Other_Web_Site"
}
}
What I need to do is retreive this Json answer, once I have it, the rest is piece of cake.
Infos :
After the PostAsync function, var res contains this :
It looks like you might not be correctly handling an asynchronous task — the WaitingForActivation message you’re seeing, rather than being a response from our API, is in fact the status of your task.
The task is waiting to be activated and scheduled internally by the .NET Framework infrastructure.
It seems you might need to await⁽²⁾ the task to ensure it completes or access the response with await client.PostAsync(url, content);. for adding await you need to add async to controller⁽¹⁾ action.
public async Task<ActionResult> Index(int idInsc) //Change here [1]
{
INSC_Inscription insc = GetMainModelInfos(idinsc);
JsonModel jm = new JsonModel();
jm.store_id = "store2";
jm.api_token = "yesguy";
jm.checkout_id = "uniqueId";
jm.txn_total = "123.00";
jm.environment = "qa";
jm.action = "preload";
var jsonObject = JsonConvert.SerializeObject(jm);
var url = "https://gatewayt.whatever.com/chkt/request/request.php";
HttpClient client = new HttpClient();
var content = new StringContent(jsonObject, System.Text.Encoding.UTF8, "application/json");
System.Threading.Tasks.Task<HttpResponseMessage> res = await client.PostAsync(url, content); //Change here [2]
insc.response = res.Result; // This cause an exeption
return View(insc);
}
This is how I would post a JSON object to somewhere using Newtonsoft.Json package, HttpClient and StringContent classes:
using Newtonsoft.Json;
var object = new Model
{
//your properties
}
var jsonObject = JsonConvert.SerializeObject(object);
var url = "http://yoururl.com/endpoint"; //<- your url here
try
{
using HttpClient client = new();
var content = new StringContent(jsonObject , Encoding.UTF8,
"application/json");
var res = await client.PostAsync(url, content);
}
Please make sure your function is async and that you await the client.PostAsync fucntion.
If someone is wondering how I finally pulled it off (with other's help) here it is :
var url = "https://gatewayt.whatever.com/chkt/request/request.php";
HttpClient client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var content = new StringContent(jsonObject, System.Text.Encoding.UTF8, "application/json");
var res = await client.PostAsync(url, content);
var jsonRes = await res.Content.ReadAsStringAsync();
This line is important var jsonRes = await res.Content.ReadAsStringAsync(); the object jsonRes will be a string value, which is actually the response. The var res will only be the status of the response, not the actual response.
I came with an issue this morning where the Api which I am calling is a Get Method but to get Get the Data from it I had to send the json body this is working good when I am testing it in the post man but I am not able to implement it in my project where I am calling this using HttpClient
here is the screenshot of post
It also have a bearer token which I pass in Authorization
Now when I am try to implement this at client side here is my code
var stringPayload = JsonConvert.SerializeObject(json);
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://myapiendpoint/serviceability/"),
Content = new StringContent(stringPayload, Encoding.UTF8, "application/json"),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
when I call this method using this code I get
System.Net.HttpStatusCode.MethodNotAllowed - Status code 405
I also tried changing this line
Method = HttpMethod.Get to Method = HttpMethod.Post
but still getting same error
I know this is bad implementation at API Side the request ideally should be POST but changing this is not in my hand and hence need to find the solution
almost search all over and trying all the variant of using GET Method finally the solution which worked for me in this case was this
var client = new HttpClient();
client.BaseAddress = new Uri("https://baseApi/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", token));
var query = new Dictionary<string, string>
{
["pickup_postcode"] = 400703,
["delivery_postcode"] = 421204,
["cod"] = "0",
["weight"] = 2,
};
var url = "methodurl";
var response = await client.GetAsync(QueryHelpers.AddQueryString(url, query));
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<MyModel>(responseBody);
Got QueryHelpers from Microsoft.AspNetCore.WebUtilities package
I want to be able to receive the Body content of a POST request inside the POST function definition in the REST API.
I have a client code that converts a C# object into JSON and then wraps it in a HTTP StringContent. This payload is then sent via a HTTP Post request to the URL. However the Post method in API always returns NULL when I try returning the received string.
Client:
public async void Register_Clicked(object sender, EventArgs e) // When user enters the Register button
{
Sjson = JsonConvert.SerializeObject(signup);
var httpContent = new StringContent(Sjson);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://apiname.azurewebsites.net");
var response = await client.PostAsync("api/values", httpContent);
var responseContent = await response.Content.ReadAsStringAsync();
StatusLabel.Text = responseContent; //To display response in client
}
}
API POST Definition:
[SwaggerOperation("Create")]
[SwaggerResponse(HttpStatusCode.Created)]
public string Post([FromBody]string signup)
{
return signup;
}
I want the clients input back as a response to be displayed in the client (StatusLabel.Text). However all I receive is NULL. Kindly guide me in the right direction.
I have prepared a simple example on how you can retrieve your Result from your Task:
async Task<string> GetResponseString(SigupModel signup)
{
Sjson = JsonConvert.SerializeObject(signup);
var httpContent = new StringContent(Sjson);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://apiname.azurewebsites.net");
var response = await client.PostAsync("api/values", httpContent);
var responseContent = await response.Content.ReadAsStringAsync();
}
return responseContent;
}
And you can call this as:
Task<string> result = GetResponseString(signup);
var finalResult = result.Result;
StatusLabel.Text = finalResult; //To display response in client
If you are not using async keyword, then you can call get your Result as:
var responseContent = response.Content.ReadAsStringAsync().Result;
EDIT
Basically you would have to POST your signup model to your API Controller. Use SigupModel signup as a parameter if you would like. Then whatever processing you are doing in the API, the final result in a string. Now this string can either be a null, empty or have a value. When you get this value in your client, you would have do the following:
var responseContent = await response.Content.ReadAsStringAsync();
var message = JsonConvert.DeserializeObject<string>(responseContent);
Here you will get your message a string and then you can set it as: StatusLabel.Text = message ;
How to consume RestApi using c# and to store the content of responses in json file? i.e When I run the program, it should call API and automatically it should store the json content in json file.
How can it be possible using Asp.Net?
You should use HTTP POST
using System.Net.Https; // Add this library
using (var client = new HttpClient())
{
var values = "DataToSend";
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://sit.com/sample.aspx", content);
var responseString = await response.Content.ReadAsStringAsync(); //JSON
}
You can call any rest api using httpclient(Microsoft.AspNet.WebApi.Client)
Following method returns a json string async which you can save later
static async Taskstring> GetContentAsync(string path)
{
using (var httpClient = new HttpClient())
return await httpClient.GetStringAsync(address);
}
to get json content synchronously
using (var client = new HttpClient())
{
var response = client.GetAsync("http://example.com").Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseString);//you can save the responseString here
}
}
or use open source library like RestSharp
var client = new RestClient("http://example.com");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
More examples can be found https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client or using restsharp