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"
}
}
Related
I can't manage to stablish a connection to Synology NAS from c# using RestSharp (or any other method)
public void TryConnection()
{
var request = new RestRequest("/webapi/entry.cgi", Method.Post);
request.AddParameter("path", "entry.cgi");
request.AddParameter("api", "SYNO.API.Info");
request.AddParameter("version", "1");
request.AddParameter("method", "query");
var client = new RestClient(new RestClientOptions("http://quickconnect.to/FDesign-GmbH:5000/") { FollowRedirects = true });
var response = client.ExecuteGetAsync(request).Result;
string s = response.ResponseUri.ToString();
}
Result = "Request failed with status code Redirect".
from what i found i believe this is having something to do with redirects but i dont know how to handle it...
if i paste this Url manualy in browser i get feedback :
https://192-168-178-23.fdesign-gmbh.direct.quickconnect.to:5001/webapi/entry.cgi?api=SYNO.API.Info&version=1&method=query
same Url in Code:
public void TryConnection()
{
var request = new RestRequest("/webapi/entry.cgi", Method.Post);
//request.AddParameter("path", "entry.cgi");
request.AddParameter("api", "SYNO.API.Info");
request.AddParameter("version", "1");
request.AddParameter("method", "query");
request.AddParameter("query", "SYNO.API.Auth,SYNO.FileStation");
var client = new RestClient(new RestClientOptions("https://192-168-178-23.fdesign-gmbh.direct.quickconnect.to:5001/") { FollowRedirects = false });
var response = client.ExecuteGetAsync(request).Result;
string s = response.ResponseUri.ToString();
}
with code i get : "Error sending request"
Some help on this would be appreciated.
//request init
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(client.BaseAddress + ""),
Content = jsonContent
};
Console.WriteLine(request.Method);
var response = await client.SendAsync(request);
Console.WriteLine(response.RequestMessage);
The Request message shows that it was sent as GET, even though I set Method to Post
I think your endpoint is doing a redirect, try turning that off via the HttpClientHandler.
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
var client = new HttpClient(handler);
// Do your work.
your code is doing the right thing. here's a console app that does the same thing, and the outcome is the right one. an Https POST call is done to the configured URL.
using System;
using System.Net.Http;
namespace testapicall
{
class Program
{
static void Main(string[] args)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://google.com")
};
Console.WriteLine(request.Method);
var response = client.SendAsync(request).GetAwaiter().GetResult();
Console.WriteLine(response.RequestMessage);
}
}
}
and here's the console log output: Method: POST, RequestUri: https://google.com/', Version: 1.1, Content: , Headers:{}
what is the resource behind the URL you're trying to call doing? Maybe it is redirecting to another resource, by doing a GET request.
I recommend to use the RestClient to execute the Rest APIs.
Please refer the following URL and sample code
https://restsharp.dev/
var client = new RestClient("URL");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("accept", "application/json");
request.AddParameter("parameter name", "values");
IRestResponse response = client.Execute(request);
var data = (JObject)JsonConvert.DeserializeObject(response.Content);
I have an API which i want to get access from one of my proxy server only. As that server have given all access to access that particular API. So I have single endpoint.
I have proxy server URL and Port and i want to add proxy settings in my app settings file and implement it so when call is given to API, that particular call pass through the Proxy server.
Please assist me how can I achieve this?
Current Call to API as below.
PushMessageAndroidRequest req = new PushMessageAndroidRequest();
req.registration_ids = list.Select(x => x.Token).ToList();
req.data = new AndroidData() { Payload = CommonLib.ConvertObjectToJson(payload) };
response = await RequestHandler.PostDataAsync<PushMessageResponse>(_appConfig.pushMessageConfigs.Url, req, new List<KeyValue>() { new KeyValue("Authorization", "key=" + _appConfig.pushMessageConfigs.Key) });
Sample code have written
public static async Task<ResJsonOutput> ProxyDataAsync(string ApiPath,string obj, List<KeyValue> Headers = null)
{
ResJsonOutput result = new ResJsonOutput();
HttpResponseMessage response = new HttpResponseMessage();
var requestUri = string.Format(ApiPath);
var request = (HttpWebRequest)WebRequest.Create(requestUri);
WebProxy myproxy = new WebProxy(Settings.ProxyAddress, Settings.ProxyPort);
myproxy.BypassProxyOnLocal = false;
request.Proxy = myproxy;
using (WebResponse response = request.GetResponse())
{
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
//JObject jResponse = JObject.Parse(stream.ReadToEnd());
//var isSuccess = jResponse.Value<bool>("success");
//result = (isSuccess) ? true : false;
}
}
return result;
}
I have been struggling to download a simple pdf hosted online using restsharp. I have been playing around with the code for over an hour and all I get are null object results.
The file downloads easily in POSTMAN using a GET and no content header set but still what gives?
Below is the noddy sandbox test I have been experimenting around with:
[TestFixture]
public class Sandbox
{
[Test]
public void Test()
{
var uri = "https://www.nlm.nih.gov/mesh/2018/download/2018NewMeShHeadings.pdf";
var client = new RestClient();
var request = new RestRequest(uri, Method.GET);
//request.AddHeader("Content-Type", "application/octet-stream");
byte[] response = client.DownloadData(request);
File.WriteAllBytes(#"C:\temp\1.pdf", response);
}
}
Update: Return a Stream
var baseUri = "https://www.nlm.nih.gov/mesh/2018/download/";
var client = new RestClient(baseUri);
var request = new RestRequest("2018NewMeShHeadings.pdf", Method.GET);
request.AddHeader("Content-Type", "application/octet-stream");
var tempFile = Path.GetTempFileName();
var stream = File.Create(tempFile, 1024, FileOptions.DeleteOnClose);
request.ResponseWriter = responseStream => responseStream.CopyTo(stream);
var response = client.DownloadData(request);
The stream is now populated with the downloaded data.
Try this:
var uri = "https://www.nlm.nih.gov/mesh/2018/download/";
var client = new RestClient(uri);
var request = new RestRequest("2018NewMeShHeadings.pdf", Method.GET);
//request.AddHeader("Content-Type", "application/octet-stream");
byte[] response = client.DownloadData(request);
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;