I have a WEB API created with .NET and I have a few POST and GET methods that I want to use in another C# Windows Form project. The GET methods work correctly but for some reason
I can't get the POST method to work as it doesn't pass the correct variables.
I have a constructor that sets the default url
client.BaseAddress = new Uri("http://localhost:7101/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
so I have this post method and the api gets the call but both the variables are equal to 0 (in the API), while in this method they are with different values (the correct ones).
Here is the API:
[HttpPost]
[Route("UpdatePercentage")]
public void UpdatePercentage(int playerid, int percentage)
{
...
}
Here is how I have used it:
var userid = 2;
var percentageText = 21;
var response = await client.PostAsJsonAsync("UpdatePercentage",
(userid, percentageText));
You have to fix two things:
You are using tuple; use an anonymous type instead.
You are passing wrong parameter names.
So fix the code like this:
var playerid = 2;
var percentage = 21;
var response = await client.PostAsJsonAsync("UpdatePercentage",
new {playerid , percentage});
OR
var userid = 2;
var percentageText = 21;
var response = await client.PostAsJsonAsync("UpdatePercentage",
new {playerid = userid , percentage = percentageText});
Example:
Assuming you have the following variables:
var x= 1;
var y = "something";
Then:
If you pass (x, y) as parameter, it will be json serialized to {"Item1":1,"Item2":"something"} which is not expected by the API.
If you pass new {x, y} as parameter, it will be json serialized to {"x":1,"y":"something"} which is expected by the API.
Related
I am new to programming and been tasked to grab data from an API.
The issue I have is basic C# returning the contents of brakeparts. I'm passing the part id and obtaining a list of brake parts correctly. I need to assign the partid to the list, which seems to work when adding a breakpoint, however how do I return this list? Return brake parts doesn't work. They could be potentially many parts it returns whilst looping I need it to append to the Parts list. I know its probably something quite simple but I can't get my head around returning back the whole list. I've tried brakeparts.AddRange(brakeparts); This doesn't work too.
private static List<Parts> getBrakeparts(List<int> partids)
{
var restClient = new RestClient("https://example.example.net/api");
foreach (var partid in partids)
{
var returnreq = new RestRequest($"/brakeparts/{partid}/ ", Method.GET);
var res = restClient.Execute(returnreq);
Parts brakeparts = JsonConvert.DeserializeObject<Parts>(res.Content);
brakeparts.PartID = partid;
}
return brakeparts;
}
As I understand, you're simply trying to return a list of parts which you want to fill with the Parts breakparts that you deserialized from the Json response.
Simply create a List<Parts> instance and add the breakparts to it in the loop.
It could look like the following.
private static List<Parts> getBrakeparts(List<int> partids)
{
var restClient = new RestClient("https://example.example.net/api");
List<Parts> parts = new List<Parts>();
foreach (var partid in partids)
{
var returnreq = new RestRequest($"/brakeparts/{partid}/ ", Method.GET);
var res = restClient.Execute(returnreq);
Parts brakeparts = JsonConvert.DeserializeObject<Parts>(res.Content);
brakeparts.PartID = partid;
parts.Add(brakeparts);
}
return parts;
}
I'm having a bit of trouble loading a JSON response from this request into a Deedle DataFrame:https://sampleserver6.arcgisonline.com/arcgis/rest/services/Earthquakes_Since1970/FeatureServer/0/query?where=OBJECTID%3C10&returnGeometry=false&f=json
In the JSON, what I'm interested are the features. More specifically, for each feature there are attributes - I want essentially just a collection of those attributes to load into a DataFrame. In this particular case, there is only one attribute "name" so my expectation is that the resulting DataFrame would have a column "name" with the values shown.
I've tried using json2csharp and creating my own class, but the result either doesn't have the column header/values or the values are missing. I'm not really sure what I'm doing wrong or if I'm even approaching this the right way. My understanding from the Deedle documentation is that it should be possible to create a DataFrame from a collection of objects: https://bluemountaincapital.github.io/Deedle/csharpframe.html#Creating-and-loading-data-frames. Certainly, using the Enumerable example listed on the page works as expected.
Here is the pertinent section of my code:
string url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Earthquakes_Since1970/FeatureServer/0/query?";
WebClient wc = new WebClient();
wc.QueryString.Add("where", "OBJECTID<10");
wc.QueryString.Add("returnGeometry", "false");
wc.QueryString.Add("f", "json");
var data = wc.UploadValues(url, "POST", wc.QueryString);
var responseString = UnicodeEncoding.UTF8.GetString(data);
JObject o = JObject.Parse(responseString);
dynamic x = JsonConvert.DeserializeObject(responseString);
var testObjList = new List<dynamic>();
foreach (dynamic element in x.features)
{
testObjList.Add(new myClass { name = element.attributes.name});
Console.WriteLine($"{element.attributes.name}");
}
var dfObjects = Frame.FromRecords(testObjList);
dfObjects.Print();
var df = Frame.FromRecords(test);
df.Print(); // No headers or values shown
where myClass is just this:
public class myClass{
public string name { get; set; }
}
Any help/pointers would be much appreciated!
The Frame.FromRecords operation relies on static type information to figure out what properties the class has. In your case, you define the list of objects as List<dynamic> - this is compiled as Object and so Deedle does not see any members.
To fix this, all you need to do is to define the type as a list of myClass objects:
var testObjList = new List<myClass>();
A more compact approach using an anonymous type would work too:
var testObjList =
((IEnumerable<dynamic>)x.features).Select(element =>
new { name = element.attributes.name });
var dfObjects = Frame.FromRecords(testObjList);
var httpClient = new HttpClient();
var response = await httpClient.GetStringAsync("http://192.168.1.57/smsapi/api/kullanici/" + viewModel.Item.ID);
var GrupKullanicilarList = JsonConvert.DeserializeObject<Kullanicilarr>(response);
---> string TelefonNoList = GetTelno(GrupKullanicilarList);
public string GetTelno(List<Kullanicilarr> GrupKullanicilarList)
{
List<string> TelefonNoList = new List<string>();
foreach (Kullanicilarr Kullanici in GrupKullanicilarList)
{
TelefonNoList.Add("<TelefonNo><TelNo>" + Kullanici.Telefonno.ToString() + "</TelNo></TelefonNo>");
}
return string.Join("\n", TelefonNoList);
It gaves an error on the Fourth line in the beginning where I put arrow:"cannot convert from 'SmsApp.Models.Kullanicilarr' to 'System.Collections.Generic.List' How should I write the last line ?
In line 3,
var GrupKullanicilarList = JsonConvert.DeserializeObject<Kullanicilarr>(response);
you are deserializing the http Response as Kullanicilarr object.
and you are passing the Kullanicilarr to GetTelno(List<Kullanicilarr> GrupKullanicilarList) which expects List of Kullanicilarr. That's why you are getting this error.
Can you check if the http response is returningList<Kullanicilarr>?
If yes then you need to change line 3 as,
var GrupKullanicilarList = JsonConvert.DeserializeObject<List<Kullanicilarr>>(response);
If not, then you need to change the method GetTelno param as
GetTelno(Kullanicilarr GrupKullanicilarList) and update its functionality since you will be getting single object instead of an array
In our company we created a custom Issues app. Additionally to using this app in the web interface, we also want to be able to change the state of an issue (new, acknowledged, test, resolved, ...) automatically via git commit hooks. The basics are working fine (ie change state, add notes, ...), but we also want to change the responsibility for the current item to a specific user. In that special case, it's the creator if this item.
My first try was the following:
var appid = 1234; var itemid = 1;
var item = podio.ItemService.GetItemByAppItemId(appid, itemid);
var update = new Item {ItemId = item.ItemId};
var creator = item.CreatedBy.Id;
var resp = update.Field<ContactItemField>("responsibility");
resp.ContactIds = new List<int>{creator.Value};
//change some other fields as well
podio.ItemService.UpdateItem(update);
This throws an "Object not found" exception, because in the resp.ContactIds one must not set the UserId but the ProfileId.
I then tried to get the ProfileId of the item-creator via
podio.ContactService.GetUserContactField(creator.Value, "profile_id");
but this also throws an exception "(Authentication as app is not allowed for this method").
So how can I get an appropriate profile id for the user when I use authentication as app?
OK, I found a workaround for it, not sure, if this is possible for other scenarios, but it works for the current case.
Instead of using the C# interface for setting the ContactIds for the ContactItemField, I set the json values directly.
var appid = 1234; var itemid = 1;
var item = podio.ItemService.GetItemByAppItemId(appid, itemid);
var update = new Item {ItemId = item.ItemId};
var creator = item.CreatedBy.Id;
var resp = update.Field<ContactItemField>("responsibility");
resp.ContactIds = new List<int>(); // set to an empty list, so that resp.Values is initialized to an empty JArray
var u = new JObject { {"value", new JObject { {"type" , "user" }, {"id", creator } } } };
responsibleField.Values.Add(u); //add the new user to the Values of the field
//change some other fields as well
podio.ItemService.UpdateItem(update);
And if I set the value with type user I can use the known userid and the API on the server takes care of the lookup.
My link is:
http://excample.com/default.aspx?param=1
I want to get "1" in link. And if my link is:
http://excample.com/default.aspx?param1=1¶m2=0
Please help me to get the values of param1 and param2. Thank you my friend !!!
I use ASP.NET C#
You can try the below code.
Uri myUri = new Uri("http://excample.com/default.aspx?param1=1¶m2=0");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");
OR
HttpContext.Current.Request.QueryString.Get("param1");
OR
Request.QueryString["param1"];
In every Request there are Form and QueryString properties.During the Request,in the Form property it contains the values which comes after submiting the form, and in QueryString it contains every parameter passed by the URL.So you need only get the QueryString from the Request and retrieve two parameters like this
var param1 = Request.QueryString["param1"]
var param2 = Request.QueryString["param2"]
You only think like this.Almost everything you need during the request is in the Request property.For parameters from query string they are in the QueryString property.
For deeply knowledge see here.https://msdn.microsoft.com/en-us/library/ms524784(v=vs.90).aspx and https://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx
You can try like this:
var uri = new Uri("http://excample.com/default.aspx?param=1");
var query = HttpUtility.ParseQueryString(uri.Query);
var par = query.Get("param");
or
var uri = new Uri("http://excample.com/default.aspx?param1=1¶m2=0");
var query = HttpUtility.ParseQueryString(uri.Query);
var par1 = query.Get("param1");
var par2 = query.Get("param2");