call api:
public TokenModelResponse GetToken(string clientId, string secret)
{
string url = _configuration.GetSection("AppConfig")["TokenApiUrl"];
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
TokenModel tokenModel = new TokenModel()
{
ClientId = clientId,
Secret = secret
};
var tokenPostModel = JsonConvert.SerializeObject(tokenModel);
// List data response.
HttpResponseMessage response = client.PostAsync("/api/Token/Authenticate", new StringContent(tokenPostModel.ToString(), Encoding.UTF8, "application/json")).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var dataObjects = response.Content.ReadAsAsync<TokenModelResponse>().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll
return dataObjects;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
return new TokenModelResponse { Message = "Fail to get token from server" };
}
//Make any other calls using HttpClient here.
//Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
}
call api with oauth 2.0:
public ValidateLoginPassword GetUserDetails(ValidateLoginPassword.In input)
{
string url = _configuration.GetSection("AppConfig")["TokenApiUrl"];
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
ValidateLoginPassword.In inputModel = new ValidateLoginPassword.In()
{
in_password = input.in_password,
in_accountcode = input.in_accountcode,
in_login_id = input.in_login_id
};
var postModel = JsonConvert.SerializeObject(inputModel);
var request = new HttpRequestMessage()
{
RequestUri = new Uri(url+"/api/DickerData/GetUserDetails"),
Method = HttpMethod.Get,
Content = new StringContent(postModel.ToString(), Encoding.UTF8, "application/json"),
};
TokenModelResponse token = GetToken("client", "RGlja2VyITIzUGFzc3cwcmQ=");
request.Headers.Add("Authorization", $"{token.Token_Type} {token.Access_Token}");
// List data response.
HttpResponseMessage response = client.SendAsync(request).Result;
client.Dispose();
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var dataObjects = response.Content.ReadAsAsync<ValidateLoginPassword>().Result;
return dataObjects;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
return new ValidateLoginPassword { System_msg = "Fail to get user details from api" };
}
}