In C#, can I set some httpclienthandler properties in Restsharp? - c#

I have the following code in C# that uses HTTPClient and I am trying to migrate to RestSharp to leverage the nice Derserialization code
here is my current code:
var httpClient = new HttpClient(new HttpClientHandler()
{
UseDefaultCredentials = true,
AllowAutoRedirect = false
});
var response = httpClient.GetStringAsync(myUrl).Result;
Here is the equivalent code using restsharp:
_client = new RestClient { BaseUrl =new Uri(myUrl) };
var request = new RestRequest { Method = method, Resource = "/project", RequestFormat = DataFormat.Json };
var response = _client.Execute(request);
but I can't figure out how to set
UseDefaultCredentials = true
and
AllowAutoRedirect = false
on the restSharp side. Is this supported?

You need provide the basic authentication information like below for RestSharp if you want to use the Basic HTTP authentication.
_client = new RestClient { BaseUrl =new Uri(myUrl) };
_client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
To use the windows authentication:
Update:
const Method httpMethod = Method.GET;
string BASE_URL = "http://localhost:8080/";
var client = new RestClient(BASE_URL);
// This property internally sets the AllowAutoRedirect of Http webrequest
client.FollowRedirects = true;
// Optionally you can also add the max redirects
client.MaxRedirects = 2;
var request = new RestRequest(httpMethod)
{
UseDefaultCredentials = true
};
client.Execute(request);

Related

Teams webhook post (proxy authentication) failed

I'm trying to post a new Teams message. If I don't use proxy, pogram fails half start count with fail: Proxy auth required. If i try to use proxy, build fail by timeout (post timeout).
Maybe some fail in proxy settings?
using (var httpClientHandler = new HttpClientHandler
{
UseDefaultCredentials = true,
UseProxy = true,
Proxy = new WebProxy { UseDefaultCredentials = true }
})
{
using (var httpClient = new HttpClient())
{
var httpResponse = await httpClient.PostAsync(HookUri, StringContent);
}
}

SharePoint 2010 ListData.svc REST API Randomly returns error: 'uriString' parameter represents an absolute URI from HTTPClient

I'm experiencing an intermittent problem with our SharePoint 2010 REST API. I have a .Net Core Console application that makes a series of calls to SharePoint List Endpoints to get a JSON response. My problem is that at random times, the API response is an error page:
A relative URI cannot be created because the 'uriString' parameter
represents an absolute URI.http://www.example.com/somefolder/file.svc
Is there a problem with my HTTPClient configuration? Is there a configuration setting that I can toggle in SharePoint to prevent the error or more reliable?
var uri = new Uri("http://www.example.com/");
var credential = new NetworkCredential("username", "password", "domain");
var credentialsCache = new CredentialCache { { uri, "NTLM", credential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
HttpClient Client = new HttpClient(handler);
Client.BaseAddress = new Uri("http://www.example.com/sharepoint/path/ListData.svc/");
// Make the list request
var result = await Client.GetAsync("MySharePointList");
To get the list items, the REST API URI like below.
http://sp2010/_vti_bin/ListData.svc/listname
Modify the code as below.
var siteUrl = "http://www.example.com/";
var listName = "MySharePointList";
var uri = new Uri(siteUrl);
var credential = new NetworkCredential("username", "password", "domain");
var credentialsCache = new CredentialCache { { uri, "NTLM", credential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(uri, "/_vti_bin/ListData.svc");
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
var requestURL = siteUrl + "/_vti_bin/ListData.svc/" + listName;
// Make the list request
var result = client.GetAsync(requestURL).Result;
var items= result.Content.ReadAsStringAsync();

Proxy authentication with Twilio voice api in C#

I want make outbound calls from my console application using C# With Twilio voice api. But most of the time i am getting the connection error message. My system is using the proxy server. So i want to add proxy authentication with the code. Please suggest.
My code is as below :
const string accountSid = "*****************";
const string authToken = "*****************";
var client = new TwilioRestClient(accountSid, authToken); TwilioClient.Init(accountSid, authToken);
var to = new PhoneNumber("*****************");
var from = new PhoneNumber("*****************"); `enter code here`
var call = CallResource.Create(to, from, url: new Uri(tempURL));
Twilio Evangelist here.
If you're trying to use the proxy here, I think using our Rest API is going to be helpful. Try this code below to hook your proxy server up to the HttpClient object:
public static HttpClient GetProxy()
{
// First create a proxy object
var proxyUri = $"{proxyServerSettings.Address}:{proxyServerSettings.Port}";
var proxyCreds = new NetworkCredential("proxyuser", "proxypassword");
var proxy = new WebProxy(proxyUri, false)
{
UseDefaultCredentials = false,
Credentials = proxyCreds,
};
// Now create a client handler which uses that proxy
var httpClientHandler = new HttpClientHandler()
{
Proxy = proxy,
PreAuthenticate = true,
UseDefaultCredentials = false,
};
return new HttpClient(httpClientHandler);
}
To make the telephone call with the proxy, you can use the sample code here:
const string accountSid = "*****************";
const string authToken = "*****************";
string to = "+1xxxxxxxxxx";
string from = "+1xxxxxxxxxx";
string callUrl = $"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Calls";
var httpClient = GetProxy();
var authorizationValue = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{accountSid}:{authToken}"));
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {authorizationValue}");
var result= httpClient.PostAsync(callUrl, new FormUrlEncodedContent(new Dictionary<string,string>
{
{"To", to},
{"From", from},
{"Url", "http://demo.twilio.com/docs/voice.xml"}
}));
Let me know if this helps or if you run into additional problems. Happy to help here

How do I call API from server side using ASP.NET MVC?

I am trying to pull REST data from an API but I need to handle the calls to the API with some server side solution. I have tried using the following code
try
{
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(60);
var request = new HttpRequestMessage()
{
RequestUri = new Uri(string.Format("https://jsonodds.com/{0}{1}{2}", "api/odds/", "?source=", "3")),
Method = HttpMethod.Get,
};
request.Headers.Add("JsonOdds-API-Key", "your key");
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
String.Format("Success");
}
}
catch (Exception ex)
{ //log error }
I receive a 407() error. Any ideas or tips how to do this?
If you are going through a proxy server then you need to use a different constructor for HttpClient.
_httpClient = new HttpClient(new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Address = new Uri(proxyUrl),
BypassProxyOnLocal = false,
UseDefaultCredentials = true
}
})
{
BaseAddress = url
};
Replace proxyUrl with your proxy address then replacing the credential with those that are valid for your proxy. This example uses the default credentials, but you can pass a NetworkCredential to the WebProxy.

HttpClient adds hostname twice when using proxy server

I am using the HttpClient class to make GET requests, it works perfectly without proxy, but when I try to make a request thought a proxy server, it adds hostname in the path and there is also hostname in headers, so the full url is like http://google.comhttp://google.com/
The code:
static void GetSmth()
{
var baseAddr = new Uri("http://google.com");
var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
UseCookies = true,
UseProxy = true,
Proxy = new WebProxy("111.56.13.168:80", true),
};
HttpClient client = new HttpClient(handler);
client.BaseAddress = baseAddr;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "/");
var resp = client.SendAsync(request).Result;
}
Wireshark screenshot:
What is wrong with it?

Categories