Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using GAMongo.Service.DynamicsCRM.Contract;
- using Newtonsoft.Json;
- using System;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading.Tasks;
- namespace GAMongo.Service.DynamicsCRM
- {
- public static class DynamicsCrmConnector
- {
- public static HttpClient GetHttpClient(string url, string username, string password)
- {
- try
- {
- HttpMessageHandler messageHandler;
- messageHandler = new OAuthMessageHandler(url, new TokenRequest() { Username = username, Password = password }, new HttpClientHandler());
- HttpClient httpClient = new HttpClient(messageHandler)
- {
- BaseAddress = new Uri(url),
- Timeout = new TimeSpan(0, 0, 30) //30 sec
- };
- return httpClient;
- }
- catch (Exception)
- {
- throw;
- }
- }
- }
- class OAuthMessageHandler : DelegatingHandler
- {
- private AuthenticationHeaderValue authHeader;
- public OAuthMessageHandler(string serviceUrl, TokenRequest tokenRequest,
- HttpMessageHandler innerHandler)
- : base(innerHandler)
- {
- var httpContent = new StringContent(JsonConvert.SerializeObject(tokenRequest), Encoding.UTF8, "application/json");
- using (HttpClient client = new HttpClient())
- {
- var response = client.PostAsync(serviceUrl + "/api/token", httpContent).Result;
- if (response.IsSuccessStatusCode)
- {
- var token = JsonConvert.DeserializeObject<string>(response.Content.ReadAsStringAsync().Result);
- authHeader = new AuthenticationHeaderValue("Bearer", token);
- }
- }
- }
- protected override Task<HttpResponseMessage> SendAsync(
- HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
- {
- request.Headers.Authorization = authHeader;
- return base.SendAsync(request, cancellationToken);
- }
- }
- }
- /Usage
- public ContactByCardResponse GetContactByCard(ContactByCardRequest request)
- {
- using (HttpClient client = DynamicsCrmConnector.GetHttpClient(_setting.Url, _setting.Username, _setting.Password))
- {
- var httpContent = new StringContent(JsonConvert.SerializeObject(request, Formatting.Indented), Encoding.UTF8, "application/json");
- var response = client.PostAsync(_setting.Url + "/api/Customer/ContactByCard", httpContent).Result;
- return JsonConvert.DeserializeObject<ContactByCardResponse>(response.Content.ReadAsStringAsync().Result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement