CRM 2016 web apis with C# - 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();
}

Related

How to send HttpClient get method autorized in .NET Core [duplicate]

I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.
My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?
This is what I have (removed personal info):
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));
var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}
A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:
{
"name": "This is my new project!",
"description": "It's going to run real smooth"
}
You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var response = await httpClient.PostAsJsonAsync(
"https://basecamp.com/[USER ID]/api/v1/projects.json",
new {
name = "My Project",
description = "My Project Description"
});
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
This posts the payload as specified in the docs and sets your user agent in the headers as it should be.

Passing Authorization Header in multiple redirects of HttpClient

I'm sending a get request to the server, the server is redirecting to 4 furthur call and then returns the response.
HttpClient gives the exception, no authorization token is provided.
Can you tell me, how to pass the same authorization token on multiple redirects? It works fine if I set "AllowAutoRedirect=false" & returns RanToComplation Status.
Here is my method :
static async Task CallWebAPIAsync()
{
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.UseDefaultCredentials = true;
webRequestHandler.AllowPipelining = true;
webRequestHandler.AllowAutoRedirect = true;
using (var client = new HttpClient(webRequestHandler))
{
client.BaseAddress = new Uri("https://apirequest");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
client.Timeout = TimeSpan.FromSeconds(30000);
//GET Method
var response = await client.GetAsync("user").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseresult = await response.Content.ReadAsStringAsync();
Console.WriteLine("Id:{0}\tName:{1}", responseresult);
}
else
{
Console.WriteLine("Internal server Error");
}
}
I think the problem may be related to this
Authorization headers must be stripped on redirects. I'm currently trying to figure out how to work around it.
I was missing the delegation handler, which will handle the redirects.
https://stackoverflow.com/a/19493338/3459965
this link helps me
Updated Code is:
static async Task CallWebAPIAsync()
{
HttpClientHandler clientHandler = new HttpClientHandler();
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.UseDefaultCredentials = true;
webRequestHandler.AllowPipelining = true;
webRequestHandler.AllowAutoRedirect = false;
webRequestHandler.Credentials = CredentialCache.DefaultCredentials;
GlobalRedirectHandler globalRedirectHandler = new GlobalRedirectHandler() { InnerHandler = webRequestHandler };
using (var client = new HttpClient(globalRedirectHandler))
{
client.BaseAddress = new Uri("https://apitest");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
client.Timeout = TimeSpan.FromSeconds(30000);
//GET Method
var response = await client.GetAsync("user").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseresult = await response.Content.ReadAsStringAsync();
Console.WriteLine("Id:{0}\tName:{1}", responseresult);
}
else
{
Console.WriteLine("Internal server Error");
}
}
}

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

How do I pass Basic Auth to a RESTful service in c#?

How do I call a RESTful service and pass in basic auth. This is username and password along with authorization basic.
using (var httpClient = new HttpClient())
{
//var request = new StringContent(messageBody);
//request.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpClient.BaseAddress = new Uri(serviceUrl);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var credentials = Encoding.ASCII.GetBytes("myadmin:mypassword");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
//var response = await httpClient.PostAsJsonAsync(serviceUrl, customer);
HttpResponseMessage response = await httpClient.PostAsJsonAsync("url here", customer);
}
You have to concatenate the username and the password with a colon, encode the value to base64 and then add this value to the Authorization header with "Basic" scheme.

HttpClient and setting Authorization headers

I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.
My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?
This is what I have (removed personal info):
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));
var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}
A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:
{
"name": "This is my new project!",
"description": "It's going to run real smooth"
}
You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var response = await httpClient.PostAsJsonAsync(
"https://basecamp.com/[USER ID]/api/v1/projects.json",
new {
name = "My Project",
description = "My Project Description"
});
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
This posts the payload as specified in the docs and sets your user agent in the headers as it should be.

Categories