I have some code:
public Task<IRestResponse> SendRequest(string url, string bodyJson)
{
var client = new RestClient(url);
var request = new RestRequest();
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.AddBody(bodyJson);
var taskCompletionSource = new TaskCompletionSource<IRestResponse>();
client.ExecuteAsync(request, response =>
{
taskCompletionSource.SetResult(response);
});
return taskCompletionSource.Task;
}
response contains all but not the answer from url (response doesnt' contain Data object). When I specify object for ExecuteAsync:
public Task<IRestResponse<MyClass>> SendRequest(string url, string bodyJson)
{
var client = new RestClient(url);
var request = new RestRequest();
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.AddBody(bodyJson);
var taskCompletionSource = new TaskCompletionSource<IRestResponse<MyClass>>();
client.ExecuteAsync<MyClass>(request, response =>
{
taskCompletionSource.SetResult(response);
});
return taskCompletionSource.Task;
}
public class MyClass
{
public bool ResultCheck { get; set; }
public string Message { get; set; }
}
in response I can find object Data (response.Data) which contains fields with values from url.
For example I receive response with Data: { ResultCheck=true, Message="Result!" }
How can I receive filled Data from url with any object without specifiing type - MyClass. I wan't to receive response with any number of fields for different urls. I want to receive some anonymous object.
One way would be to use Generics and dynamic objects. This should allow you to specify any object type to be converted to a response.
You can therefore change the method to
public Task<IRestResponse<T>> SendRequest<T>(string url, string bodyJson)
{
var client = new RestClient(url);
var request = new RestRequest
{
RequestFormat = DataFormat.Json;
Method = Method.POST;
};
request.AddBody(bodyJson);
var taskCompletionSource = new TaskCompletionSource<IRestResponse<T>>();
client.ExecuteAsync<T>(request, response =>
{
taskCompletionSource.SetResult(response);
});
return taskCompletionSource.Task;
}
Then we can create temp object using dynamic. We can then fill this will all the information we need
// Create temp obj
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
finally at the call site we state the type is dynamic. Hopefully the rest api can forward this onto the client and they can retrieve the object as type dynamic.
SendRequest<dynamic>(url, JsonConvert.SerialiseObject(employee));
The client can then do something like
dynamic response = GetResponse(...);
var name = response.Name;
Related
in my App when I send parameters on my Microsoft Flows HTTP request it sends a reply that on the JSON string below is my code. how can I get the value of the status?
Am I lacking something to get the "No data met the criteria" value?
public async Task<IActionResult> SendNameAge()
{
using (var client = new HttpClient())
{
// Create new instance of Person
Person person = new Person
{
Name = SD.HTTPName,
Age = SD.HTTPAge
};
var personJSON = JsonConvert.SerializeObject(person);
var buffer = System.Text.Encoding.UTF8.GetBytes(personJSON);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.BaseAddress = new Uri(SD.ApiUri);
var response = await client.PostAsync(SD.ApiUri, byteContent);
string jsonstatus = response.Content.ReadAsStringAsync().Result;
return Ok(response);
}
}
I need to get the "No data met the criteria" response from the HTTP request
This is from the Postman test
I have call to REST service from jscript that works fine:
post('/MySite/myFunct', { ID:22 })
How to make this call from C# in most native c# way?
UPD:
I need HTTPS solution also.
UPD:
And I need to use cookies
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "ID", "22" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com", content);
var responseString = await response.Content.ReadAsStringAsync();
Old traditional way is using HttpClient / HttpWebRequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/Test/TestPostData");
request.Method = "POST";
SampleModel model = new SampleModel();
model.PostData = "Test";
request.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var sw = new StreamWriter(request.GetRequestStream()))
{
string json = serializer.Serialize(model);
sw.Write(json);
sw.Flush();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Apart from this I prefer more Restclient /Restsharp from nuget.
A simple example of post request will be like this
using RestSharp;
using RestTest.Model;
private void button1_Click(object sender, EventArgs e)
{
var client = new RestClient();
var request = new RestRequest();
request.BaseUrl = "http://carma.org";
request.Action = "api/1.1/searchPlants";
request.AddParameter("location", 4338);
request.AddParameter("limit", 10);
request.AddParameter("color", "red");
request.AddParameter("format", "xml");
request.ResponseFormat = ResponseFormat.Xml;
var plants = client.Execute<PowerPlantsDTO>(request);
MessageBox.Show(plants.Count.ToString());
}
You can use HTTP Verbs directly from call
A Post example:
public void Create(Product product)
{
var request = new RestRequest("Products", Method.POST); < ----- Use Method.PUT for update
request.AddJsonBody(product);
client.Execute(request);
}
A Delete Example
public void Delete(int id)
{
var request = new RestRequest("Products/" + id, Method.DELETE);
client.Execute(request);
}
For adding header in request
request.AddHeader("data", "test");
A Get Request
private RestClient client = new RestClient("http://localhost:8080/api/");
RestRequest request = new RestRequest("Products", Method.GET);
RestResponse<YourDataModel> response = client.Execute<YourDataModel>(request);
var name = response.Data.Name;
I am trying to send dictionary using POST in C# to a django server.
The server receives the request and acknowledges with 200 message, however it receives an empty Multi Value Dictionary.
Here is the client sending POST request.
public class Hello1
{
public static void Main()
{
Console.WriteLine("Request Initiating");
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["key1"] = "test";
data["key2"] = "TEST2";
data["key3"] = "NA";
string url = "http://10.34.150.153:8000/key_detect/detect/";
var response = wb.UploadValues(url, "POST", data);
string result = System.Text.Encoding.UTF8.GetString(response);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
See this post:
POSTing JSON to URL via WebClient in C#
You need to serialize your data to JSON before you upload it.
var data = new NameValueCollection();
data["key1"] = "test";
data["key2"] = "TEST2";
data["key3"] = "NA";
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(data);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
I am a newbie to Mailgun and REST and need some help.
If I use the Mailgun provided code:
RestClient client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "xxxx");
RestRequest request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "me#mydomain.com");
return client.Execute(request);
How do I retrieve and process the response that the address is valid or not?
This code works for me. I didn't use RESTClient and wrote my own code(which works perfectly fine)
[System.Web.Services.WebMethod]
public static object GetEmailInfo(string UserName)
{
var http = (HttpWebRequest)WebRequest.Create("https://api.mailgun.net/v2/address/validate?address=" + UserName);
http.Credentials = new NetworkCredential("api","public key");
http.Timeout = 5000;
try
{
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JSON.JsonObject js = new JSON.JsonObject(content);
return Convert.ToBoolean(js["is_valid"]);
}
catch (Exception ex)
{
}
}
First of You should never post private information such as your public key of such API
Just by using the amazing Postman Chrome app you can see the result of such request:
click here to see the image below in full resolution
and I'm sure, if you instead of return client.Execute(request); you do
var result = client.Execute(request);
return result;
and adding a breakpoint in the return you can inspect what is the object that is passed from the call... without testing, I'm sure you can convert result.Content (as it's where RestSharp appends the response content) into an object and use that object (or use the dynamic type).
now, testing your code in VS:
click here to see the image below in full resolution
you can then use the dynamic object like:
click here to see the image below in full resolution
public void GetResponse()
{
var client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "pubkey-e82c8201c292691ad889ace3434df6cb");
var request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "me#mydomain.com");
var response = client.Execute(request);
dynamic content = Json.Decode(response.Content);
bool isValid = content.is_valid;
string domain = content.parts.domain;
}
and treat the content of the response just like the json passed:
{
"address": "me#mydomain.com",
"did_you_mean": null,
"is_valid": true,
"parts": {
"display_name": null,
"domain": "mydomain.com",
"local_part": "me"
}
}
When I use code below from REST Sharp I am not able to pass listOfSelectedTicketsIds it always null.
Request of Rest Sharp .net Client
var _stDeveloperApi = new RestClient("http://127.0.0.1/");
var url = string.Format("api/v1/SignalR/MultiClickMode");
var listOfSelectedTicketsIds = new List<int> { 2, 3 };
var request = new RestRequest(url, Method.GET);
request.AddParameter("listOfSelectedTicketsIds", listOfSelectedTicketsIds, ParameterType.GetOrPost);
var response = _stDeveloperApi.Execute(request);
Web API Method
[HttpGet]
public HttpResponseMessage MultiClickMode(List<int> listOfSelectedTicketsIds)
{
var response = new HttpResponseMessage();
try
{
}
catch (Exception ex)
{
response = Request.CreateResponse(HttpStatusCode.InternalServerError);
}
return response;
}
Change your client code like this.
var _stDeveloperApi = new RestClient("http://127.0.0.1/");
var url = string.Format("api/v1/SignalR/MultiClickMode");
var listOfSelectedTicketsIds = new List<int> { 2, 3 };
var request = new RestRequest(url, Method.GET);
listOfSelectedTicketsIds.ForEach(t =>
request.AddParameter(
"listOfSelectedTicketsIds", t, ParameterType.GetOrPost));
var response = _stDeveloperApi.Execute(request);
Change the web API action method signature like this.
public HttpResponseMessage MultiClickMode(
[FromUri]List<int> listOfSelectedTicketsIds)