i use asp.net mvc and c#,
i my bank setion project i use this code for banking
var requestContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("amount", payment.Amount), //i want change this section for <string,int>
new KeyValuePair<string, string>("transid", "id"),
new KeyValuePair<string, string>("pin","pin" )
});
var client = new HttpClient();
HttpResponseMessage response = await client.PostAsync("http://address.com/api/verify/", requestContent);
HttpContent responseContent = response.Content;
string result = "";
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
result = await reader.ReadToEndAsync();
}
now my bank scenario is change and i should pass integer for amount,how i can do i from mycode?
because FormUrlEncodedContent accept <string,string>
thank you for your help
Try this, It is working for me.
public class PaymentActionsRequest
{
[JsonProperty("payment_intent")]
public string PaymentIntent { get; set; }
[JsonProperty("amount")]
public long Amount { get; set; }
}
var keyValueContent = PaymentActionsRequest.ToKeyValue();
var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
You need to use something like Amount.ToString() as this content would eventually be string/encoded as part of POST body.
Related
I am beginner in using this api and it's services. I have tried lots of thing but nothing worked for me, Just wanted to push silent notification. Any suggestion will be appreciated and Thanks in advance.
private static readonly string oneSignalUrl = "https://onesignal.com/api/v1/notifications";
public async Task<HttpResponseMessage> SendNotification(string playerId, string notificationAppId, string notificationSecretKey)
{
var client = new HttpClient();
client.BaseAddress = new Uri(oneSignalUrl);
client.DefaultRequestHeaders.Add("authorization", "Basic " + notificationSecretKey);
var model = new DictionaryDTO { aps = new Dictionary<string, int>() { { "content-available", 1 } }, acme1 = "logout" };
var content = GetContent(notificationAppId, model, playerId);
var response = await client.PostAsync(oneSignalUrl, content);
return response;
}
public StringContent GetContent(string notificationAppId, DictionaryDTO model, string playerId)
{
var content = new StringContent(JsonConvert.SerializeObject(new
{
app_id = notificationAppId,
contents = new
{
en = "Testing the push notification functionality",
model
},
include_player_ids = new string[] { playerId }
}), Encoding.UTF8, "application/json");
return content;
}
I am having trouble inserting data into a MongoDB from a windows form application through a rest API. Below is what I have so far.
ProductController (API)
[HttpPost]
public JsonResult Post(Product item)
{
MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("AppConString"));
dbClient.GetDatabase("motopartsdb").GetCollection<Product>("products").InsertOne(item);
return new JsonResult("Added Successfully");
}
WindowsApplication
async private void createProduct()
{
var values = new Dictionary<string, string>
{
{ "name", ProductNameInput.Text },
{ "category", category},
{ "type", "New" },
{ "supplier", SupplierInput.Text },
{ "quantity", QuantityInput.Text },
{ "price", PriceInput.Text },
{ "condition", "" },
{ "description", DescriptionInput.Text }
};
HttpClient client = new HttpClient();
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://localhost:57501/api/product", content);
var responseString = await response.Content.ReadAsStringAsync();
}
When I run the code I get error 415 from the rest API, I tried possible fixes but cant seem to figure it out.
Any help is appreciated, many thanks.
I would recommend that you don't send a Dictionary<string, string> but a Product object.
Below is an untested example, I am guessing your Product object properties.
EDITED
I have edited the below code to Serialize the product and generated StringContent to send.
async private void createProduct()
{
Product prod = new Product()
{
Name = ProductNameInput.Text,
Category = category,
Type = "New" ,
Supplier = SupplierInput.Text ,
Quantity = QuantityInput.Text ,
Price = PriceInput.Text ,
Condition = "" ,
Description = DescriptionInput.Text
};
HttpClient client = new HttpClient();
StringContent stringContent = null;
if (prod != null)
{
//serialize object to string in Json format
string content = JsonConvert.SerializeObject(prod, _jsonSerializerSettings);
//create content
stringContent = new StringContent(content, Encoding.UTF8, "application/json");
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
var response = await client.PostAsync("https://localhost:57501/api/product", stringContent);
var responseString = await response.Content.ReadAsStringAsync();
}
In addition you may need to
add a JSON request header to your HttpClient
set your Mongo DB Convention. For example I use Camel Case.
//clear accept headers
client.DefaultRequestHeaders.Accept.Clear();
//add accept json
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//an example C# object
public class MyExample
{
//camel case in mongoDB saved as firstName
public string FirstName {get; set;}
}
//on Mongo DB create
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
I am learning as I create, that being said, I have spent quite a few hours on JUST the login/register pages in the app I am trying to make.
I have finally got to the point where I am able to make the API call to get the response back with the information I need.
I just don't know how to save the token once it comes back.
I am using SQLite for local storage, and I have a "Token" nclass to save it to, but I can't figure out how to actually save it and continue forward.
(I could be completely wrong and it doesn't work at all, but that's all part of learning, I guess.)
anyways, here is my Token class
public class Token
{
[PrimaryKey]
public int Id { get; set; }
public string accessToken { get; set; }
public string errorDescription { get; set; }
public DateTime expireDate { get; set; }
public int expireIn { get; set; }
public Token() { }
}
and here is my APIServices class (some stuff is commented because I am working with my buddy to get everything sorted on the API side)
public class ApiServices
{
public string JsonResult { get; private set; }
public async Task<bool> RegisterUserAsync(string email, string name, /*string first_name, string last_name,*/ string password)
{
var client = new HttpClient();
var model = new RegisterBindingModel
{
Email = email,
//FirstName = first_name,
//LastName = last_name,
Name = name,
Password = password,
};
var json = JsonConvert.SerializeObject(model);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("https://myurl/v1/auth/register", httpContent);
if (response.IsSuccessStatusCode)
{
var result = JsonConvert.DeserializeObject(JsonResult);
return true;
}
return false;
}
public async Task<string> LoginAsync(string email, string password)
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("email", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
var request = new HttpRequestMessage(HttpMethod.Post, "https://myurl/auth/login" + "Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(content);
var accessTokenExpiration = jwtDynamic.Value<DateTime>(".expires");
var accessToken = jwtDynamic.Value<string>("access_token");
//Settings.AccessTokenExpirationDate = accessTokenExpiration;
Debug.WriteLine(accessTokenExpiration);
Debug.WriteLine(content);
return accessToken;
}
}
Lets explain it step by step:
1.Install the sqlite-net-pcl package(Nuget URL). This package will help you to work with database in an easy way.
2.After installing it successfully, You need to add the using statement of SQLite to your class:
using SQLite;
3.In order to make a request to database, you will need to first make a connection to database. to do so, you need to declare a variable for aforementioned goal:
var db = new SQLiteConnection (dbPath);
4.Once you have the database connection object, you are ready to make requests to database. for example to save an object of type Token class, just do this:
var tokenInfo= new Token();
tokenInfo.accessToken="...";//set value to other properties like this
db.Insert(tokenInfo);
These are all you need to do an Insert request to database!
You might want to read more about aforementioned package in these urls:
https://github.com/praeclarum/sqlite-net
https://learn.microsoft.com/en-us/xamarin/android/data-cloud/data-access/using-sqlite-orm
I am trying to get this azure API to work:
https://learn.microsoft.com/en-us/rest/api/machinelearning/webservices/createorupdate
The following code runs a GET request which returns successfully (200 OK and return body), but the Put request to the exact same uri at the bottom fails with a 400 "Bad request".
The code inbetween basically just unwraps the json output of the first request and tried to send the same unchanged data in the input format of the PUT on the same uri.
Could anyone help me see why this fails?
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await httpClient.GetAsync($"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.MachineLearning/webServices/{serviceName}?api-version=2016-05-01-preview");
var json = await response.Content.ReadAsStringAsync();
var f = JsonConvert.DeserializeObject<WebService>(json);
var requestBody = new RequestBody()
{
location = f.Location,
name = f.Name,
tags = f.Tags,
properties = f.Properties
};
var jsoncontent = JsonConvert.SerializeObject(requestBody, Formatting.None);
var content = new StringContent(jsoncontent, Encoding.UTF8, "application/json"); //tried simpler things like "{\"location\":\"West Europe\"}" with no result
var response2 = await httpClient.PutAsync($"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.MachineLearning/webServices/{serviceName}?api-version=2016-05-01-preview", content, new JsonMediaTypeFormatter());
// last line returns a 400 bad request only.
And then I use this custom object;
private class RequestBody
{
public string location { get; set; }
public string name { get; set; }
public WebServiceProperties properties { get; set; }
public IDictionary<string, string> tags { get; set; }
}
It seems it was one of those obvious things.
The ", new JsonMediaTypeFormatter()" snippet at the end ruined it. Removing it fixed the issue and it returns 200 OK without it.
I'm currently working with a console app which I'm using the HttpClient to interact with an Apache CouchDB database. I'm using this article: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
I'd like to ignore the null properties in my class when I'm serializing and sending a document to my database via the PostAsJsonSync but I'm not sure how:
public static HttpResponseMessage InsertDocument(object doc, string name, string db)
{
HttpResponseMessage result;
if (String.IsNullOrWhiteSpace(name)) result = clientSetup().PostAsJsonAsync(db, doc).Result;
else result = clientSetup().PutAsJsonAsync(db + String.Format("/{0}", name), doc).Result;
return result;
}
static HttpClient clientSetup()
{
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("**************", "**************");
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("*********************");
//needed as otherwise returns plain text
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
Here's the class I'm serializing....
class TestDocument
{
public string Schema { get; set; }
public long Timestamp { get; set; }
public int Count { get; set; }
public string _rev { get; set; }
public string _id { get; set; } - would like this to be ignored if null
}
Any help much appreciated.
Assuming that you are using Json.NET to serialize your object, you should use the NullValueHandling property of the JsonProperty attribute
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
Check out this great article and the online help for more details
If you need this behavior for all the properties of all the classes you're going to send (which is exactly the case that has led me to this question), I think this would be cleaner:
using ( HttpClient http = new HttpClient() )
{
var formatter = new JsonMediaTypeFormatter();
formatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
TestDocument value = new TestDocument();
HttpContent content = new ObjectContent<TestDocument>( value, formatter );
await http.PutAsync( url, content );
}
This way there's no need to add attributes to your classes, and you still don't have to serialize all the values manually.
use HttpClient.PostAsync
JsonMediaTypeFormatter jsonFormat = new JsonMediaTypeFormatter();
jsonFormat.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;
jsonFormat.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
HttpResponseMessage res = c.PostAsync<T>(url, TObj, jsonFormat).Result;
I'm not sure you can do that with the PutAsJsonAsync as you have it right now. Json.NET can do this though, if you're able to use it, and a NuGet package exists if it helps. If you can use it, I'd rewrite the InsertDocument function to look like:
public static HttpResponseMessage InsertDocument(object doc, string name, string db)
{
HttpResponseMessage result;
string json = JsonConvert.SerializeObject(doc, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
if (String.IsNullOrWhiteSpace(name)) result = clientSetup().PostAsync(db, new StringContent(json, null, "application/json")).Result;
else result = clientSetup().PutAsync(db + String.Format("/{0}", name), new StringContent(json, null, "application/json")).Result;
return result;
}