C
C#ā€¢4mo ago
K.F

API integration issue in .NET core framework.

Hello everyone. I am a beginner of .NET core and I need to integrate other platform inside of .net core project. I have this other site API docs and have credentials. I need to request with token on header for this request, but not sure how can I implement this feature. Many thanks.
72 Replies
blueberriesiftheywerecats
HttpClient Class (System.Net.Http)
Provides a class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
blueberriesiftheywerecats
You can use this class to send http request
douchebag
douchebagā€¢4mo ago
public Stream HttpRequest(string url, string token, string method, JObject requestObj) { string baseUrl = url; string finalUrl = baseUrl; HttpWebRequest httpWebRequest = HttpWebRequest.CreateHttp(finalUrl); httpWebRequest.Method = method; httpWebRequest.Headers.Add("Authentication", token); httpWebRequest.ContentType = "application/json"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(requestObj); streamWriter.Flush(); streamWriter.Close(); } WebResponse webResponse = httpWebRequest.GetResponseAsync().Result; var response = webResponse.GetResponseStream(); return response; } @K.F
Angius
Angiusā€¢4mo ago
JObject? HttpWebRequest? Tf is this?
douchebag
douchebagā€¢4mo ago
sample
Angius
Angiusā€¢4mo ago
It's a shit sample
douchebag
douchebagā€¢4mo ago
dont mind it
Angius
Angiusā€¢4mo ago
It's doing the opposite of helping
douchebag
douchebagā€¢4mo ago
is it wrong @ZZZZZZZZZZZZZZZZZZZZZZZZZ
Angius
Angiusā€¢4mo ago
It's a sample of how to write shit code that uses deprecated APIs Yes it is HttpWebRequest has been deprecated long ago
douchebag
douchebagā€¢4mo ago
deprecated hahaah yah sorry
Angius
Angiusā€¢4mo ago
JObject is just getting rid of type safety for no reason It's some 2000-ass code, the question was about .NET Core
douchebag
douchebagā€¢4mo ago
oh my JObject is old?
Angius
Angiusā€¢4mo ago
It was never necessary to begin with
douchebag
douchebagā€¢4mo ago
so what do you suggest generic type?
Angius
Angiusā€¢4mo ago
And, yes, .NET has a built-in Json serializer too, so Newtonsoft is not needed A generic would be better, yes
douchebag
douchebagā€¢4mo ago
but it is not dynamic
Angius
Angiusā€¢4mo ago
Also, your code uses .Result instead of being async Why the fuck would you want to use dynamic
douchebag
douchebagā€¢4mo ago
for easy code
Angius
Angiusā€¢4mo ago
For shit code
douchebag
douchebagā€¢4mo ago
hahahha
Angius
Angiusā€¢4mo ago
That's slow and impossible to reason about
douchebag
douchebagā€¢4mo ago
really? oh my i wish i never met Newtonsoft
Angius
Angiusā€¢4mo ago
Newtonsoft doesn't use dynamic far as I know It was good when .NET had no built-in Json serializer Now it's just largely unnecessary, and slower than the native serializer Not inherently bad tho
douchebag
douchebagā€¢4mo ago
i see. but how do you know its slower?
Angius
Angiusā€¢4mo ago
Benchmarks
douchebag
douchebagā€¢4mo ago
oh Thanks @ZZZZZZZZZZZZZZZZZZZZZZZZZ how bout this private static string HttpPostRequest(string url, string data, string authorization) { string finalUrl = url; HttpRequestMessage httpRequestMessage = new HttpRequestMessage() { }; httpRequestMessage.Content = new StringContent(data, Encoding.UTF8, "application/json"); httpRequestMessage.Method = HttpMethod.Post; httpRequestMessage.Headers.Add("Authorization", authorization); httpRequestMessage.RequestUri = new Uri(finalUrl); HttpClient httpClient = new HttpClient() { Timeout = TimeSpan.FromMinutes(5) }; HttpResponseMessage httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result; using (StreamReader reader = new StreamReader(httpResponseMessage.Content.ReadAsStream())) { return reader.ReadToEnd(); } }
K.F
K.Fā€¢4mo ago
Thanks @douchebag , @ZZZZZZZZZZZZZZZZZZZZZZZZZ , @blueberriesiftheywerecats I will implement with this way and then let you know. And many thanks @douchebag šŸ‘
Angius
Angiusā€¢4mo ago
Yeah don't use the code above
K.F
K.Fā€¢4mo ago
what's matter @ZZZZZZZZZZZZZZZZZZZZZZZZZ ?
Angius
Angiusā€¢4mo ago
Not at my PC right now so can't elaborate, but it's not good code It's using .Result so it's blocking, it does a bunch of unnecessary stuff with the request, a bu ch of unnecessary stuff with the response And in the end produces a strong instead of something more useful
K.F
K.Fā€¢4mo ago
I am getting response from third-party api as JSON. In this case StreamReader is good choice?
Angius
Angiusā€¢4mo ago
It's unnecessary Chances are, you can just use await client.GetFromJsonAsync<T>() and get a proper object back
K.F
K.Fā€¢4mo ago
basic work flow is like this. First, get an access token with your credentials. Second, get data from the API with an authentication request with an authentication token. But responses are all JSON type and need to send it to frontend side as JSON type. I'd like to make this as service on project but most important is which structure could be best for this implementation. I am new .NET and have experience with REST API according to tutorials.
douchebag
douchebagā€¢4mo ago
Stack Overflow
Await on a completed task same as task.Result?
I'm currently reading "Concurrency in C# Cookbook" by Stephen Cleary, and I noticed the following technique:
var completedTask = await Task.WhenAny(downloadTask, timeoutTask);
if (completedTas...
douchebag
douchebagā€¢4mo ago
@K.F change it to await Make sure you have async function
K.F
K.Fā€¢4mo ago
Yes, I am currently using async function on my side.
douchebag
douchebagā€¢4mo ago
Check this one @K.F , there is also request header here So you're a backend dev. Ic Ok guys, bye
K.F
K.Fā€¢4mo ago
Yes, as far as I checked HttpClient Class is good choice, I guess.
blueberriesiftheywerecats
There is also this library that helps you write meaningful and compact code for requests https://github.com/reactiveui/refit
GitHub
GitHub - reactiveui/refit: The automatic type-safe REST library for...
The automatic type-safe REST library for .NET Core, Xamarin and .NET. Heavily inspired by Square's Retrofit library, Refit turns your REST API into a live interface. - reactiveui/refit
K.F
K.Fā€¢4mo ago
private async Task AuthenticateAsync() { using (var httpsClient = new HttpClient()) { Console.WriteLine( _username); var response = await httpsClient.PostAsync($"{_uri}/identity/realms/fintatech/protocol/openid-connect/token", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("username", _username), new KeyValuePair<string, string>("password", _password), new KeyValuePair<string, string>("grant_typpe", "password"), new KeyValuePair<string, string>("client_id", "app-cli") })); Console.WriteLine("authentication response", response); response.EnsureSuccessStatusCode(); var authResponse = JsonConvert.DeserializeObject<AuthResponse>(await response.Content.ReadAsStringAsync()); _accessToken = authResponse.AccessToken; _refreshToken = authResponse.RefreshToken; } } Here is my approach to get auth token. With postman, I tested it with my test credential and received tokens but I am getting 400 error with current code. uri: https://platform.fintacharts.com username: [email protected] password: kisfiz-vUnvy9-sopnyv
K.F
K.Fā€¢4mo ago
No description
blueberriesiftheywerecats
Its 200? Wym And also you leaked your password and refresh token so you better change those Oh you mean with your code its 400 400 means you have wrong request Check response, there should be problem written And your uri seems wrong
K.F
K.Fā€¢4mo ago
Okay thanks. let me check again. I checked console but there is empty
K.F
K.Fā€¢4mo ago
No description
blueberriesiftheywerecats
Are you sure you are sending your request to correcut uri? Oh i see You misspelled grant_type @K.F
K.F
K.Fā€¢4mo ago
Awesome to figure out it. šŸ‘ But still not get auth token But it appears 400 error is disappeared
blueberriesiftheywerecats
What is the issue?
K.F
K.Fā€¢4mo ago
authentication response is empty
K.F
K.Fā€¢4mo ago
No description
blueberriesiftheywerecats
Well, c# cant just convert your object to string, you either override ToString method in AuthResponse or use debugger(better approach) Im sure you have response $debug
MODiX
MODiXā€¢4mo ago
Tutorial: Debug C# code and inspect data - Visual Studio (Windows)
Learn features of the Visual Studio debugger and how to start the debugger, step through code, and inspect data in a C# application.
blueberriesiftheywerecats
Im not sure if
response
response
type have tostring overrided So just use debugger and check
authResponse
authResponse
K.F
K.Fā€¢4mo ago
well still not getting result.
No description
blueberriesiftheywerecats
No, Console.WriteLine automatically calls the ToString method, and because its not overrided you wouldnt see anything Use debugger to see everything in your variables
K.F
K.Fā€¢4mo ago
I am afraid if it is possible to debug for web api
blueberriesiftheywerecats
Yes You just have to put breakpoint before return And then run debug I mean before or just on Console.WriteLine(authResponse)
K.F
K.Fā€¢4mo ago
No description
K.F
K.Fā€¢4mo ago
Yes, I am getting nothing as I debugged
blueberriesiftheywerecats
Well i see that content length is 2744 Which means there is something Check authResponse
K.F
K.Fā€¢4mo ago
authResponse is null
K.F
K.Fā€¢4mo ago
No description
blueberriesiftheywerecats
Yes, because it has wrong definition To be able to deserialize from json your class must have properties that have the same name as json fields In your case it should be smth like
class AuthResponse
{
public string access_token { get; set }
...
}
class AuthResponse
{
public string access_token { get; set }
...
}
Or you can use JsonPropertyName attribute if you want to change your properties name in c# but still get the value from json
K.F
K.Fā€¢4mo ago
Fantastic, you are the god of .net. šŸ‘ It worked
blueberriesiftheywerecats
šŸ˜† and how am i still jobless
K.F
K.Fā€¢4mo ago
I can't believe you are jobless now jorking? šŸ™‚ seems like yelling me
blueberriesiftheywerecats
Lol i think no one wants to accept my resume because im still underage
K.F
K.Fā€¢4mo ago
well, are you still student?
blueberriesiftheywerecats
Not yet, i mean i just graduated from school
K.F
K.Fā€¢4mo ago
I see, I can work with you but let me your expectation
Angius
Angiusā€¢4mo ago
JsonConvert Any reason to use Newtonsoft?
douchebag
douchebagā€¢4mo ago
JsonSerializer.Deserialize<model>(jsonString);
Want results from more Discord servers?
Add your server