Unable to use HTTP2 in HttpClient .Net - c#

I'm trying to request data over HTTP 2.0. I'm using the HttpClient from .Net 5. I'm on Windows 10. The problem is that the version on the response seems to always be "1.1". What am I doing wrong here?
var httpClient = new HttpClient();
string authToken = "{jwt token}";
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
var req = new HttpRequestMessage(HttpMethod.Get, "{url}")
{
Version = new Version(2, 0)
};
var x = httpClient.SendAsync(req).ConfigureAwait(false).GetAwaiter().GetResult();
var version = x.Version;
Console.WriteLine(version);

Related

Is there a way to convert C# HttpClient to curl?

Imagine you are making a HTTP request for example (though it could be any http call):
string baseurl = LocalConfigKey.BaseUrl;
string geturl = string.Format("{0}leo-platform-api/api/v1/Orchestrator/Endpoint", baseurl);
var response = string.Empty;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", LocalConfigKey.APIMSubscriptionKey);
HttpResponseMessage result = httpClient.GetAsync(geturl).GetAwaiter().GetResult();
result.EnsureSuccessStatusCode();
if (result.IsSuccessStatusCode)
{
response = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
Is it possible to generate curl out of this request that can be logged in a db etc ?
You can use this package to convert HTTPClient to curl:
First install NuGet package:
dotnet add package HttpClientToCurl
Example:
Declare request requirements:
string requestBody = #"{ ""name"" : ""amin"",""requestId"" : ""10001000"",""amount"":10000 }";
string requestUri = "api/test";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri);
httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
using var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://localhost:1213");
Get curl from request
httpClient.GenerateCurlInConsole(httpRequestMessage, requestUri ); // Generate curl in console
httpClient.GenerateCurlInFile(httpRequestMessage, requestUri ); // Generate curl in file
HTTP call
// Call PostAsync => await client.PostAsync(requestUri, httpRequest.Content);
To get more information see the repo GitHub docs

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

I can not authorize to hitbtc api from c#

my code is:
HitBtcApi.HitBtcApi hitbtc = new HitBtcApi.HitBtcApi();
hitbtc.Authorize("xxx", "xxx");
RestRequest request2 = new RestRequest("/api/2/account/balance", method.GET);
var x= await hitbtc.Execute(request2, true);
MessageBox.Show(x.content.ToString());
this error rising when running:
{"error":{"code":1001,"message":"Authorization required","description":""}} but when i use "/api/2/public/symbol" instead of "/api/2/account/balance" it work. please help me. thanks.
Did you activate the access right to the specific API for your API key?
https://hitbtc.com/settings/api-keys
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new
System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
Encoding.ASCII.GetBytes(
"user:pass")));
var result = await (await client.GetAsync("https://api.hitbtc.com/api/2/trading/balance")).Content
.ReadAsStringAsync();
}

NTLM authentication HttpClient in Core

I am trying to use the HttpClient to access a REST service which requires NTLM authentication. However I keep getting a 401 Unauthorized.
My code looks like this
private static void Main()
{
var uri = new Uri("http://localhost:15001");
var credentialsCache = new CredentialCache { { uri, "NTLM", CredentialCache.DefaultNetworkCredentials } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
var httpClient = new HttpClient(handler) { BaseAddress = uri, Timeout = new TimeSpan(0, 0, 10) };
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = httpClient.GetAsync("api/MyMethod").Result;
}
My target framework is netcoreapp2.0. If I change to net461, it will work. Not sure what I am doing wrong?
Microsoft has accepted this as a bug. Possibly a fix will be released with core 2.1
https://github.com/dotnet/corefx/issues/25988

CRM 2016 web apis with C#

We have CRM 2016 on premise and want to consume the API using c# :
var credentials = new NetworkCredential(username, password);
HttpClient client = new HttpClient(new HttpClientHandler() {Credentials = credentials});
client.BaseAddress = new Uri("https://xxx.elluciancrmrecruit.com/api/data/v8.0/datatel_events");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("datatel_events?$orderby=datatel_eventname").Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsStringAsync();
}
else
{
//Something has gone wrong, handle it here
}
But it always return HTML page says try later instead of the json response.
You should query the OData endpoint to get the information you are looking for assuming date1_events is a custom entity (although the naming convention seems to be off).
As an example to query contacts:
var credentials = new NetworkCredential(username, password);
var client = new HttpClient(new HttpClientHandler() {Credentials = credentials})
{
BaseAddress = new Uri("https://xxx.elluciancrmrecruit.com/api/data/v8.0/")
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("accounts?$top=1").Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsStringAsync();
}

Categories