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));
{
Related
I am using RestSharp to create a RestRequest
It seems pretty simple and straight forward.
The issue i noticed though is that when developing the object that will be a part of the body of the payload, a key, is called "params".
If you didnt know. Params is a keyword. How do i create a payload to properly implement, despite the fact a key could be special for the C# language?
var payload = new {
data = "",
command = new {
name = "Foo",
params = "Bar"
}
};
RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST);
request.Resource = "";
request.AddBody(payload);
var result = Client.Execute(request);
You can just put # before params :
var payload = new {
data = "",
command = new {
name = "Foo",
#params = "Bar"
}
};
I've tested it and the outputted JSON will be params without the #.
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?
I have Dictionary with values how to convert them to string of format application/json and application/x-www-form-urlencoded simplest standard way:
var values = new Dictionary<string, string>
{
{"id", "1"},
{"amount", "5"}
};
The same question regarding class object with the same fields:
class values
{
public String id { get; set; }
public string amount { get; set; }
}
simple way is using json.NET library in order to post the data. you can convert your object to application/json like this:
var jsonString = JsonConvert.SerializeObject(values);
then post it to your service like this:
private static T Call<T>(string url, string body)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 60 * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "POST";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
responseString = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(responseString);
}
It's not clear from your question if you want to manually serialize your dictionary or object and then send it using a custom way or if you would like to automatically serialize and send them to a web service.
The manual way:
Json
PM > Install-Package Newtonsoft.Json
Json.NET natively supports dictionary to Json object and, of course, object to json object serialization. You simply install it and than serialize using:
var jsonString = JsonConvert.SerializeObject(values); // values can be Dictionary<string, Anything> OR an object
Result:
{
"id": "1",
"amount", "5"
}
Form URL encoded
The cleanest way is to use the .NET built-in utility HttpUtility.ParseQueryString (which also encodes any non-ASCII character):
var nvc = HttpUtility.ParseQueryString("");
foreach(var item in values)
nvc.Add(item.Key, item.Value);
var urlEncodedString = nvc.ToString();
Result:
id=1&amount=5
Please note that there is no direct way to serialize an object into a Form URL encoded string without adding its members manually, e.g.:
nvc.Add(nameof(values.id), values.id);
nvc.Add(nameof(values.amount), values.amount);
The automatic way:
Everything is simpler if you just use HttpClient:
PM > Install-Package Microsoft.AspNet.WebApi.Client
Json
You may need to also use HttpClientExtensions extension methods for automatic Json serialization (without it you need to serialize it manually as shown above):
using (var client = new HttpClient())
{
// set any header here
var response = await client.PostAsJsonAsync("http://myurl", values); // values can be a dictionary or an object
var result = await response.Content.ReadAsAsync<MyResultClass>();
}
Form URL encoded
using (var client = new HttpClient())
{
using (var content = new FormUrlEncodedContent(values)) // this must be a dictionary or a IEnumerable<KeyValuePair<string, string>>
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var response = await client.PostAsync(url, content);
var result = await response.Content.ReadAsAsync<MyResultClass>();
}
}
This way you may serialize dictionaries directly. Again for objects you need to convert them manually as shown above.
recently i discovered this amazing cms called Directus, where you can manage your database and Tables with web request and Json.
Everything worked fine creating,updating,reading...till i came to the point where i want to Create (Upload) a Image using WebRequest.
Im basicly reading a image as Base64 and writing the data along with the parameters in the Uri using a simple GET request exactly like described in API.
Regardless what i try and use the Images Never show up in my Files.
Am i doing something wrong or forgetting something?
Or does directus want something else from me?
My first try:
public static async void UploadUserImage() {
var uri = "http://IP/Directus/api/1/files?access_token=SecretApiKey";
var data = GetImageData();
var finalUri = $"{uri}&data={data}";
using (var client = new HttpClient()) {
var responseString = await client.GetStringAsync(finalUri);
Console.Write(responseString);
}
}
My Second try with Json:
public static async void UploadUserImage() {
var uri = "http://IP/Directus/api/1/files?access_token=SecretApiKey";
var data = GetImageData();
var finalUri = $"{uri}&data={data}";
var postModel = new PictureModel {
data = data,
title = "Test",
name = "test"
};
using (var client = new HttpClient())
{
// Serialize our concrete class into a JSON String
var content = JsonConvert.SerializeObject(postModel);
var contenta = new StringContent(content, Encoding.UTF8, "application/json");
var response = await client.PostAsync(finalUri, contenta);
var result = await response.Content.ReadAsByteArrayAsync();
Console.Write(System.Text.Encoding.UTF8.GetString(result));
}
}
The docs is incorrect it's actually a POST request. Thanks for pointing that out.
To upload a new file you need three provide three values:
{
"name": "image.png",
"type": "image/png",
"data": "base64content"
}
The data content has to be in this format data:<mime-type>;base64,<data-content> so it will look something like this: data:image/png;base64,ThisIsABase64Content
We are updating the docs and removing the data:image/png which is unnecessary.
var client = new RestClient("http://10.0.2.2:50670/api");
var request = new RestRequest("Inventory", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
// execute the request to return a list of InventoryItem
RestResponse<JavaList<InventoryItem>> response = (RestResponse<JavaList<InventoryItem>>)client.Execute<JavaList<InventoryItem>>(request);
The content returned is a JSON string, an array of objects. The following is a short excerpt of it:
[{"Id":1,"Upc":"1234567890","Quantity":100,"Created":"2012-01-01T00:00:00","Category":"Tequila","TransactionType":"Audit","MetaData":"PATRON 750ML"},{"Id":2,"Upc":"2345678901","Quantity":110,"Created":"2012-01-01T00:00:00","Category":"Whiskey","TransactionType":"Audit","MetaData":"JACK DANIELS 750ML"},{"Id":3,"Upc":"3456789012","Quantity":150,"Created":"2012-01-01T00:00:00","Category":"Vodka","TransactionType":"Audit","MetaData":"ABSOLUT 750ml"}]
The error message:
Operation is not valid due to the current state of the object
What is wrong here? My InventoryItem has the same properties as each object in the JSON string. Am I missing a step?
I suspect that SimpleJson, used in RestSharp can't deserialise to a JavaList.
First I would try deserialising to a:
List<InventoryItem>
Failing that, I recommend ServiceStack.Text - .Net's fastest JSON library; and do:
var response = client.Execute(request);
var thingYouWant = JsonSerializer.DeserializeFromString<List<InventoryItem>>(response.Content);
This is actually what I do myself.
Edit (Thank you to commentators):
In newer versions this would now be:
var deserializer = new JsonDeserializer();
deserializer.Deserialize<List<InventoryItem>>(response);
Failing w/ auto-magic casting, I use this in a pinch:
var rc = new RestClient("https://api-ssl.bitly.com");
var rr = new RestRequest("/v3/link/clicks?access_token={access_token}&link={bitlyUrl}", Method.GET);
rr.AddUrlSegment("bitlyUrl", bitlyUrl);
rr.AddUrlSegment("access_token", BityAccessToken);
var response = rc.Execute(rr);
dynamic json = Newtonsoft.Json.Linq.JObject.Parse(response.Content);
var clicks = Convert.ToInt32(json.data.link_clicks.Value);