Passing a nested Dictionary to web API - c#

I am using a Post method to send data to a web API. Something like this:
string apiUrl = serviceAddress;
var client = new HttpClient();
var DObject = new Dictionary<string, string>()
{
{"UserId", UserID},
{"Type", "109" },
{"Id", templateID},
{"Subject", subjectofEmail},
{"Data", #"'Name','Payman','Family','Payman'"}
};
var content = new FormUrlEncodedContent(DObject);
var response = client.PostAsync(apiUrl, content);
The problem is that, the Data object is also a dictionary. So, I have problem sending data. What is the solution?

Related

Simple HttpRequestMessage but not working

I'm writing a simple dotnet core API, under search controller which like below :
[HttpGet("order")]
public async Task <Order> SearchOrder(string ordername, int siteid) {
return await service.getorder(ordername,siteid)
}
The swagger UI where the path https://devehost/search/order test pretty work, but when I use another client to call this api by below
client = new HttpClient {
BaseAddress = new Uri("https://devehost")
};
var request = new HttpRequestMessage(HttpMethod.Get, "Search/order") {
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>> {
new("ordername", "pizza-1"),
new("siteid", "1"),
})
};
var response = await client.SendAsync(request);
The status code always return bad request. But the postman is work, can I know the problem inside?
Thank you
For a GET request, the parameters should be sent in the querystring, not the request body.
GET - HTTP | MDN
Note: Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined.
For .NET Core, you can use the Microsoft.AspNetCore.WebUtilities.QueryHelpers class to append the parameters to the URL:
Dictionary<string, string> parameters = new()
{
["ordername"] = "pizza-1",
["siteid"] = "1",
};
string url = QueryHelpers.AppendQueryString("Search/order", parameters);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = await client.SendAsync(request);

Move Json Object From One Site To Another

I have two project in asp.net webforms with different url. I need to move c# object from one to the other. I tried to serialize it to JSON with JavaScriptSerializer and move it as parameter in the url, but I don't want the client would see the json
A a = new A()
{
val = 1,
val1 = "very long string"
};
var jsonSerialiser = new JavaScriptSerializer();
string data = jsonSerialiser.Serialize(a);
Response.Redirect(service.RedirectToCheckout("http://localhost:44316/PageOnOtherSite.aspx?data=" + data));
Any ideas?
simple post request using HttpClient
using(var client = new HttpClient())
{
response = await httpClient.PostAsync(uri, new StringContent(data));
{

preparing Json Object for HttpClient Post method

I am trying to prepare a JSON payload to a Post method. The server fails unable to parse my data. ToString() method on my values would not convert it to JSON correctly, can you please suggest a correct way of doing this.
var values = new Dictionary<string, string>
{
{
"type", "a"
}
, {
"card", "2"
}
};
var data = new StringContent(values.ToSttring(), Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var response = client.PostAsync(myUrl, data).Result;
using (HttpContent content = response.content)
{
result = response.content.ReadAsStringAsync().Result;
}
You need to either manually serialize the object first using JsonConvert.SerializeObject
var values = new Dictionary<string, string>
{
{"type", "a"}, {"card", "2"}
};
var json = JsonConvert.SerializeObject(values);
var data = new StringContent(json, Encoding.UTF8, "application/json");
//...code removed for brevity
Or depending on your platform, use the PostAsJsonAsync extension method on HttpClient.
var values = new Dictionary<string, string>
{
{"type", "a"}, {"card", "2"}
};
var client = new HttpClient();
using(var response = client.PostAsJsonAsync(myUrl, values).Result) {
result = response.Content.ReadAsStringAsync().Result;
}
https://www.newtonsoft.com/json use this.
there are already a lot of similar topics.
Send JSON via POST in C# and Receive the JSON returned?
values.ToString() will not create a valid JSON formatted string.
I'd recommend you use a JSON parser, such as Json.Net or LitJson to convert your Dictionary into a valid json string. These libraries are capable of converting generic objects into valid JSON strings using reflection, and will be faster than manually serialising into the JSON format (although this is possible if required).
Please see here for the JSON string format definition (if you wish to manually serialise the objects), and for a list of 3rd party libraries at the bottom: http://www.json.org/

.NET HttpClient add query string and JSON body to POST

How do I set up a .NET HttpClient.SendAsync() request to contain query string parameters and a JSON body (in the case of a POST)?
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
var request = new HttpRequestMessage(HttpMethod.Post, "something");
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// How do I add the queryString?
// Send the request
client.SendAsync(request);
Every example I've seen says to set the
request.Content = new FormUrlEncodedContent(queryString)
but then I lose my JSON body initialization in the request.Content
I ended up finding Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString() that was what I needed. This allowed me to add the query string parameters without having to build the string manually (and worry about escaping characters and such).
Note: I'm using ASP.NET Core, but the same method is also available through Microsoft.Owin.Infrastructure.WebUtilities.AddQueryString()
New code:
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
// This is the missing piece
var requestUri = QueryHelpers.AddQueryString("something", queryString);
var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// Send the request
client.SendAsync(request);
I can suggest that you use RestSharp for this purpose. It's basically a wrapper of the HttpWebRequest that does exactly what you want: makes it easy to compose url and body parameters and deserialize the result back.
Example from the site:
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
IRestResponse response = client.Execute(request);
This is simple and works for me:
responseMsg = await httpClient.PostAsJsonAsync(locationSearchUri, new { NameLike = "Johnson" });
The body of the requests look like { NameLike:"Johnson" }

Send and receive a post variable

I'm trying to send a post variable to the url which I'm redirecting to.
I'm currently using the Get method and sending it like this:
// Redirect to page with url parameter (GET)
Response.Redirect("web pages/livestream.aspx?address="+ ((Hardwarerecorders.Device)devices[arrayIndex]).streamAddress);
And retrieving it like this:
// Get the url parameter here
string address = Request.QueryString["address"];
How do I convert my code to use the POST method?
B.T.W., I don't want to use a form to send the post variable.
Using HttpClient:
To send POST query:
using System.Net.Http;
public string sendPostRequest(string URI, dynamic content)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://yourBaseAddress");
var valuesAsJson = JsonConvert.SerializeObject(content);
HttpContent contentPost = new StringContent(valuesAsJson, Encoding.UTF8, "application/json");
var result = client.PostAsync(URI, contentPost).Result;
return result.Content.ReadAsStringAsync().Result;
}
Where 'client.PostAsync(URI, contentPost)' is where the content is being sent to the other website.
On the other website, an API Controller needs to be established to receive the result, something like this:
[HttpPost]
[Route("yourURI")]
public void receivePost([FromBody]dynamic myObject)
{
//..
}
However, you might also want to look into using a 307 re-direct, especially if this is a temporary solution.
https://softwareengineering.stackexchange.com/a/99966
using System.Net.Http;
POST
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
GET
using (var client = new HttpClient())
{
var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx");
}
My Personal Choice is Restsharp it's fast but for basic operations you can use this

Categories