I have been working on using a Rest Api for authentication (https://api.vorexlogin.com/)
So far I have added the RestSharp library to dismiss errors to RestClient and RestRequest.
So far when I run the code that I have in the textbox I get this:
RestSharp.Response
The Response that is needed should be something like:
"success": true,
"result": {
"accessToken": "eyJhbGtccccc.xxxx.yyyyzzzzz",
"refreshToken": "67ZYfdsJFDKLS879337937DKJSDLGFSDFRDEMO=",
"accessTokenExpireOn": "2021-07-03T22:19:23.8330686Z",
"refreshTokenExpireOn": "2021-08-02T21:49:23.8330686Z"
}
Even if it failed it should still be a json file of some sort. I will provide my code below.
private async void button1_Click(object sender, EventArgs e)
{
var client = new RestClient("https://api.vorexlogin.com/v2/security/authenticate");
var request = new RestRequest("resources", Method.Post);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("accept", "application/json");
request.AddParameter("application/x-www-form-urlencoded",
"grantType=password&userName=+"+ usernametbx + "&password=" + passwordtbx + "&tenant=" + tenanttbx, ParameterType.RequestBody);
var response = await client.PostAsync<IRestResponse>(request);
textBox1.Text = response.ToString();
}
public class IRestRepsonseList
{
public string accessToken { get; set; }
public string refreshToken { get; set; }
public string accessTokenExpireOn { get; set; }
public string refreshTokenExpireOn { get; set; }
}
public class IRestResponse
{
public bool success { get; set; }
public List<IRestRepsonseList> result { get; set; }
}
By using PostAsync<T> you tell RestSharp to deserialize the response to T. Your IRestResponse class doesn't implement ToString(), so the default object.ToString is used by your code, which just returns the instance class name.
I cloud also suggest you read the documentation, as you wrote lots of unnecessary code.
Here is an example of what you should be doing:
var client = new RestClient("https://api.vorexlogin.com/v2/security/authenticate");
var request = new RestRequest("resources", Method.Post)
.AddParameter("grantType", "password")
.AddParameter("userName", usernametbx)
.AddParameter("password", passwordtbx)
.AddParameter("tenant", tenanttbx);
var response = await client.PostAsync(request);
textBox1.Text = response.Content;
Related
I am trying to fix a payment Api using visual studio c#, but I am getting 400 error message, it says that one or more validation error occurred.
please what could be my mistake?
I tried running the code in postman, and it worked fine.
Below is my code sample:
public class Root
{
public string amount { get; set; }
public string email { get; set; }
public string currency { get; set; }
public string initiate_type { get; set; }
public string transaction_ref { get; set; }
public string callback_url { get; set; }
}
var client = new RestClient("https://sandbox-api-d.squadco.com/transaction/initiate");
var rootObj = new Root
{
amount = "1000",
email = EmailV,
currency = "NGN",
initiate_type = "inline",
transaction_ref = "213445RT",
callback_url = "https://samplesite.com"
};
//serialization using Newtonsoft JSON
string JsonBody = JsonConvert.SerializeObject(rootObj);
var request = new RestRequest();
request.Method = Method.Post;
request.AddHeader("Authorization", "sandbox_sk_3fae7c45922315aa8cb2a16db028f50a596d5fbdf351");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", JsonBody, ParameterType.RequestBody);
RestResponse response = client.Execute(request);
Based on their doc, the amount is decimal
https://squadinc.gitbook.io/squad/payments/initiate-payment#sample-request
so you can try changing to decimal
var rootObj = new Root
{
amount = 1000,
I am trying to get a REST API to feed into https://www.scheduleit.com/faq/10640/is-there-a-rest-api-or-webhooks
I have the get working, put the post I always get
"{"status": "error", "status_code": "404", "message": "Not Found - Invalid End Point for Method POST"}"
Code is
var client = new RestClient("https://www.scheduleit.com/api/");
var request = new RestRequest(this.TokenEndPoint, Method.POST);
//client.Authenticator = new HttpBasicAuthenticator(userName, password);
request.AddHeader("Authorization", "Basic xxxxxxxxxxxxxxxxxxxxxxxxx");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("Cache-Control", "no-cache");
request.AddParameter("title", "Title Test");
request.AddParameter("owner", "813");
request.AddParameter("date_start", "2022-12-05");
request.AddParameter("date_end", "2022-12-06");
IRestResponse response = client.Execute(request);
Any suggestions
Have tried various ways of coding
The endpoint you specified doesn't exist. You need to include the resource target;
/api/groups
/api/resources
/api/events
/api/labels
/api/reports
You also need to pass arguments in a JSON Body, not as query parameters.
This is how it should look;
public class RequestBody {
[JsonPropertyName("title")]
public string Title { get; set; }
[JsonPropertyName("owner")]
public string Owner { get; set; }
[JsonPropertyName("date_start")]
public DateTime DateStart { get; set; }
[JsonPropertyName("date_end")]
public DateTime DateEnd { get; set; }
}
var body = new RequestBody {
Title = "Title Test",
Owner = "813",
DateStart = Date.Now(),
DateEnd = Date.Now()
};
var client = new RestClient("https://www.scheduleit.com/api/events");
var request = new RestRequest().AddJsonBody(body);
var response = await client.PostAsync(request, CancellationToken.None);
I have a route in my web service that receives POST request with Json body and returns simple array in Json format. I'm using PostMan for testing route and it works perfectly. but when I'm using RestSharp it doesn't get any content (or data in deserialization case).
Here is my C# code :
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
string bodyraw = JsonConvert.SerializeObject(user)
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.Parameters.Clear();
request.AddParameter("application/json", bodyraw, ParameterType.RequestBody);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteTaskAsync<Profile>(request);
return response.Data.Address;
}
And here is the Profile Class:
public class Profile
{
public string Name { get; set; }
public string Family { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Postal_code { get; set; }
public string Education { get; set; }
public string Gender { get; set; }
public string Age { get; set; }
public string Default_contact { get; set; }
public override string ToString()
{
return string.Concat(Name," " ,Family, " ", Address);
}
}
And this is PostMan OutPut:
{
"Name": "Holma",
"Family": "Kool",
"Email": "dr#gmail.com",
"Mobile": "09063094744",
"Address": "some city- basic av. sq 60",
"Postal_code": "10246666",
"Education": "1",
"Gender": "male",
"Age": "35"
}
And the PHP code that I used is:
function silverum_update_user_profile($request ){
$parameters = $request->get_json_params();// this is a WordPress method and works just fine
$name=sanitize_text_field($parameters['name']);
$family=sanitize_text_field($parameters['family']);
$email=sanitize_text_field($parameters['email']);
$mobile=sanitize_text_field($parameters['mobile']);
$address=sanitize_text_field($parameters['address']);
$postal_code=sanitize_text_field($parameters['postal_code']);
$education=sanitize_text_field($parameters['education']);
$gender=sanitize_text_field($parameters['gender']);
$age=sanitize_text_field($parameters['age']);
$extdp = [
"Name"=>$name,
"Family"=>$family,
"Email"=>$email,
"Mobile"=>$mobile,
"Address"=>$address,
"Postal_code"=>$postal_code,
"Education"=>$education,
"Gender"=>$gender,
"Age"=>$age
];
return $extdp;
}
When PHP method returns "Parameter" its OK and both PostMan and RestSharp can see output content but when method Returns new Array only PostMan is able to recive returnd object. I spent a couple of hour on the issue but didn't get anywhere. help please.
Try using the AddJsonBody() method within the RestRequest object as opposed to adding the parameter manually.
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.AddJsonBody(user);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteAsync<Profile>(request);
return response.Data.Address;
}
Making a windows phone application and although I may easily pull from my Web Api I am having trouble posting to it. Whenever posting to the api I get the "Unsupported Media Type" error message and I'm not sure as to why it is happening considering the class I using as the base for my JSON post is the same as the one used in the api.
PostQuote (Post Method)
private async void PostQuote(object sender, RoutedEventArgs e)
{
Quotes postquote = new Quotes(){
QuoteId = currentcount,
QuoteText = Quote_Text.Text,
QuoteAuthor = Quote_Author.Text,
TopicId = 1019
};
string json = JsonConvert.SerializeObject(postquote);
if (Quote_Text.Text != "" && Quote_Author.Text != ""){
using (HttpClient hc = new HttpClient())
{
hc.BaseAddress = new Uri("http://rippahquotes.azurewebsites.net/api/QuotesApi");
hc.DefaultRequestHeaders.Accept.Clear();
hc.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await hc.PostAsync(hc.BaseAddress, new StringContent(json));
if (response.IsSuccessStatusCode)
{
Frame.Navigate(typeof(MainPage));
}
else
{
Quote_Text.Text = response.StatusCode.ToString();
//Returning Unsupported Media Type//
}
}
}
}
Quotes and Topic (Model)
public class Quotes
{
public int QuoteId { get; set; }
public int TopicId { get; set; }
public string QuoteText { get; set; }
public string QuoteAuthor { get; set; }
public Topic Topic { get; set; }
public string QuoteEffect { get; set; }
}
//Topic Model//
public class Topic
{
public int TopicId { get; set; }
public string TopicName { get; set; }
public string TopicDescription { get; set; }
public int TopicAmount { get; set; }
}
You should set the media type when creating StringContent
new StringContent(json, Encoding.UTF32, "application/json");
I found this question while working on a quick and dirty reverse proxy. I needed form data and not JSON.
This did the trick for me.
string formData = "Data=SomeQueryString&Foo=Bar";
var result = webClient.PostAsync("http://XXX/api/XXX",
new StringContent(formData, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
To fix the unsupported media type I had to use HttpRequestMessage and add header to accept json with MediaTypeWithQualityHeaderValue like bellow.
var httpRequestMessage = new HttpRequestMessage
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var httpResponse = await _client.PostAsync("/contacts", httpRequestMessage.Content);
I'm trying to do a very simple example of using RestSharp's Execute method of querying a rest endpoint and serializing to a POCO. However, everything I try results in a response.Data object that has all properties with a NULL value.
Here is the JSON response:
{
"Result":
{
"Location":
{
"BusinessUnit": "BTA",
"BusinessUnitName": "CASINO",
"LocationId": "4070",
"LocationCode": "ZBTA",
"LocationName": "Name of Casino"
}
}
}
Here is my test code
[TestMethod]
public void TestLocationsGetById()
{
//given
var request = new RestRequest();
request.Resource = serviceEndpoint + "/{singleItemTestId}";
request.Method = Method.GET;
request.AddHeader("accept", Configuration.JSONContentType);
request.RootElement = "Location";
request.AddParameter("singleItemTestId", singleItemTestId, ParameterType.UrlSegment);
request.RequestFormat = DataFormat.Json;
//when
Location location = api.Execute<Location>(request);
//then
Assert.IsNotNull(location.LocationId); //fails - all properties are returned null
}
And here is my API code
public T Execute<T>(RestRequest request) where T : new()
{
var client = new RestClient();
client.BaseUrl = Configuration.ESBRestBaseURL;
//request.OnBeforeDeserialization = resp => { resp.ContentLength = 761; };
var response = client.Execute<T>(request);
return response.Data;
}
And finally, here is my POCO
public class Location
{
public string BusinessUnit { get; set; }
public string BusinessUnitName { get; set; }
public string LocationId { get; set; }
public string LocationCode { get; set; }
public string LocationName { get; set; }
}
Additionally, the ErrorException and ErrorResponse properties on the response are NULL.
This seems like a very simple case, but I've been running around in circles all day! Thanks.
What is the Content-Type in the response? If not a standard content type like "application/json", etc. then RestSharp won't understand which deserializer to use. If it is in fact a content type not "understood" by RestSharp (you can verify by inspecting the Accept sent in the request), then you can solve this by doing:
client.AddHandler("my_custom_type", new JsonDeserializer());
EDIT:
Ok, sorry, looking at the JSON again, you need something like:
public class LocationResponse
public LocationResult Result { get; set; }
}
public class LocationResult {
public Location Location { get; set; }
}
And then do:
client.Execute<LocationResponse>(request);