C# - Problems on Connect to Synology NAS with Restsharp - c#

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.

Related

HttpRequestMessage.Method set to Post, but it Gets instead

//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);

Send parameters & file in Request Body with Origin Request Header C#

I am trying to send parameters & file in Request Body with Origin Request Header C# Console / Asp.Net (Web Form) Web Application.
I have looked around many examples but I didn't get proper solutions.
I've tried with the following code which is almost working. The only issue with couldn't get any solution to send the file in Request Body.
public class requestObj
{
public string langType { get; set; }
}
protected void CreateUser_Click(object sender, EventArgs e)
{
try
{
var requestObj = new requestObj
{
langType = "aaa"
};
var client = new RestSharp.RestClient(url);
client.Timeout = -1;
var request = new RestSharp.RestRequest(RestSharp.Method.POST);
request.AddHeader("Origin", "http://localhost:8080");
request.AddJsonBody(requestObj);
var response = client.Execute(request);
}
catch (Exception ex)
{
throw ex;
}
}
Thanks,
I have made it working following ways,
string url = requestUrl;
string filePath = #"F:\text.txt";
var client = new RestSharp.RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Origin", "http://localhost:2020");
request.AddParameter("parameter", "parameterValue");
request.AddFile("file", filePath, "text/plain"); //file parameter.
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

How to redirect call to API from particular proxy server?

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;
}

How to create a post to LinkedIn

We are getting a HTTP error 400 Bad Request while creating the Post in linkedin using HTTP POST request.
Sample COde:
public static bool PostLinkedInNetworkUpdate(string accessToken, string title, string submittedUrl = "", string submittedImageUrl = "")
{
var requestUrl = String.Format(linkedinSharesEndPoint, accessToken);
var message = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new Dictionary<string, string>
{ { "title", title },
{ "submitted-url", submittedUrl },
{"submitted-image-url" , submittedImageUrl}
},
visibility = new
{
code = "anyone"
}
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{ "Content-Type", "application/json" },
{ "x-li-format", "json" },
{"Host", "api.linkedin.com"}
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response.ContainsKey("updateKey");
}
}
We are getting an error message on the line:
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
as HTTP Error 400 Bad Request.
We have tested the code with GET Request which is working from my Dev server,However any of the POST requests are failing with this error message.
We have verified the REsponse headers with the request made from POSTMAN which is working.The response headers of POSTMAN are matching with the Bad Request response
Do we need to install the LinkedIn certificate in the Server?
Does anyone have any suggestions/comments?
Thanks in advance

mailgun email validation response

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"
}
}

Categories