C
C#16mo ago
GIGA BRAIN

❔ Getting information from web api

So I created my own web api and am creating a console application that can consume the api. I'm currently running them in two separate solutions, where the web api is on so i can access the local host on my console application. I'm currently having trouble trying to return all entries in that when I call my function that gets all entries, I get a message that its processing and sending the request, and that's it. Can someone look over my code for the method please? https://paste.mod.gg/vrqvhehmayuy/0
BlazeBin - vrqvhehmayuy
A tool for sharing your source code with the world!
66 Replies
GIGA BRAIN
GIGA BRAINOP16mo ago
Also is there any point in having asynchronous calls if this isn't a front end web app?
Denis
Denis16mo ago
Yes there is a point for async calls. Your api will have more than one client. So, your app must handle multiple requests to a single endooint Suggest adding the server code too Have you tried debuggingit? You can run multiple apps in visual studio and select which ones get the debugger attached
GIGA BRAIN
GIGA BRAINOP16mo ago
mm what server code would I add? it's a very basic basic api
Denis
Denis16mo ago
Or you can start the app manually and attach later with Shift+Alt+P
GIGA BRAIN
GIGA BRAINOP16mo ago
i tried doing the run multiple apps in visual studio and it only ran the web api
Denis
Denis16mo ago
Well let's see the code that handles the endpoint you are trying to reach from the client How did you set it up?
GIGA BRAIN
GIGA BRAINOP16mo ago
BlazeBin - huazdopymmjt
A tool for sharing your source code with the world!
GIGA BRAIN
GIGA BRAINOP16mo ago
i added my scaffolded controller solution explorer -> solution properties -> startup project -> multiple startup projects -> select both the UI and console app and have them as start i got a screenshot of what it looked like yesterday, let me look for it someone just ended up telling me to run two separate solutions
GIGA BRAIN
GIGA BRAINOP16mo ago
Denis
Denis16mo ago
And what actions can you select other than start?
GIGA BRAIN
GIGA BRAINOP16mo ago
start without debugging or none
Denis
Denis16mo ago
Interesting And if you point breakpoints? And then start? From what I've seen, you are not calling your api correctly Install postman, for exanple
GIGA BRAIN
GIGA BRAINOP16mo ago
i haven't tried breakpoints yet, i'm assuming I would put one at this line:
var result = await _httpClient.GetFromJsonAsync<List<ShiftDTO>>(link);
var result = await _httpClient.GetFromJsonAsync<List<ShiftDTO>>(link);
yup i got postman
Denis
Denis16mo ago
The link is incorrect And via postman what url works for you?
GIGA BRAIN
GIGA BRAINOP16mo ago
Denis
Denis16mo ago
Are you able to connect to the server?
GIGA BRAIN
GIGA BRAINOP16mo ago
yeah
GIGA BRAIN
GIGA BRAINOP16mo ago
Denis
Denis16mo ago
Weird
GIGA BRAIN
GIGA BRAINOP16mo ago
it's weird, i used this exact code in my program.cs before moving everything over and injecting the httpclient and it worked fine did i inject my httpclient incorrectly? i was following the documentation for injecting httpclientfactory and followed along
using System.Net.Http.Headers;
using System.Net.Http.Json;
using ShiftLoggerUI.Models;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using ShiftLoggerUI.Views;
using ShiftLoggerUI.Controllers;

// Create and host the container.
HostApplicationBuilder builder = Host.CreateApplicationBuilder();

// Tell the container what classes you want to use in DI.
builder.Services.AddSingleton<Menu>();
builder.Services.AddSingleton<Helpers>();
// not sure on this one since helpers will contain httpclient calls but is also a singleton
builder.Services.AddHttpClient<Helpers>();

// Tell the container to figure out the web of dependencies for classes
var host = builder.Build();

// Use the host(container) to give an instance of the menu class so we can call its methods
var menu = host.Services.GetRequiredService<Menu>();

// Application root; the call has everything it needs from the DI container
menu.ShowMenu();
using System.Net.Http.Headers;
using System.Net.Http.Json;
using ShiftLoggerUI.Models;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using ShiftLoggerUI.Views;
using ShiftLoggerUI.Controllers;

// Create and host the container.
HostApplicationBuilder builder = Host.CreateApplicationBuilder();

// Tell the container what classes you want to use in DI.
builder.Services.AddSingleton<Menu>();
builder.Services.AddSingleton<Helpers>();
// not sure on this one since helpers will contain httpclient calls but is also a singleton
builder.Services.AddHttpClient<Helpers>();

// Tell the container to figure out the web of dependencies for classes
var host = builder.Build();

// Use the host(container) to give an instance of the menu class so we can call its methods
var menu = host.Services.GetRequiredService<Menu>();

// Application root; the call has everything it needs from the DI container
menu.ShowMenu();
this is my program.cs
Denis
Denis16mo ago
And what does your client get as a result? Try running the server by starting it manually And run the console with some breakpoints
GIGA BRAIN
GIGA BRAINOP16mo ago
yeah im running the server manually atm
Denis
Denis16mo ago
Maybe your client is crashing Or.not getting data in the expected format
GIGA BRAIN
GIGA BRAINOP16mo ago
ok i see that my result is null
GIGA BRAIN
GIGA BRAINOP16mo ago
GIGA BRAIN
GIGA BRAINOP16mo ago
the header knows that i'm expecting a json back, it's just not writing to the result I feel like my logic for that line of code is correct though i'm awaiting the client to get the json and return a list of shift objects using the provided localhost link and I can see that it sends the get request, it's just that nothing is coming back maybe it is a server issue that i need to look into more
Denis
Denis16mo ago
You need to step to the next line, because result wants evaluated yet
GIGA BRAIN
GIGA BRAINOP16mo ago
dangit thanks for the pointout if i put a breakpoint after, the program finishes running it doesn't even access the foreach loop
Denis
Denis16mo ago
Huh Wrap that in a try catch
GIGA BRAIN
GIGA BRAINOP16mo ago
Denis
Denis16mo ago
Remember to add (Exception e) to the catch block Your server crashes too?
GIGA BRAIN
GIGA BRAINOP16mo ago
server works completely fine still up gonna add the try catch now
Denis
Denis16mo ago
I haven't touched REST in some time....is there a way to send a get request without expecting JSON to be returned? Asking so that you can see the raw incoming data
GIGA BRAIN
GIGA BRAINOP16mo ago
public async Task showEntries()
{
try
{
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

var result = await _httpClient.GetFromJsonAsync<List<ShiftDTO>>(link);

foreach (var res in result)
{
Console.WriteLine("---------------------------------");
Console.WriteLine($"ID: {res.Id}");
Console.WriteLine($"Name: {res.Name}");
Console.WriteLine($"Date: {res.Date}");
Console.WriteLine($"Hours worked: {res.HoursWorked}");
}
Console.WriteLine("---------------------------------");
}
catch (Exception e)
{
Console.WriteLine($"processing failed: {e.Message}");
}
}
public async Task showEntries()
{
try
{
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

var result = await _httpClient.GetFromJsonAsync<List<ShiftDTO>>(link);

foreach (var res in result)
{
Console.WriteLine("---------------------------------");
Console.WriteLine($"ID: {res.Id}");
Console.WriteLine($"Name: {res.Name}");
Console.WriteLine($"Date: {res.Date}");
Console.WriteLine($"Hours worked: {res.HoursWorked}");
}
Console.WriteLine("---------------------------------");
}
catch (Exception e)
{
Console.WriteLine($"processing failed: {e.Message}");
}
}
Denis
Denis16mo ago
Maybe it is ina different format than your dto model
GIGA BRAIN
GIGA BRAINOP16mo ago
does this look about right? my DTO model is the exact same as my regular model
Denis
Denis16mo ago
Yeah Try running
GIGA BRAIN
GIGA BRAINOP16mo ago
does it make a difference if my web api is using a local sql server db?
Denis
Denis16mo ago
nope it shouldn't You could try and modify the server to return some test data
GIGA BRAIN
GIGA BRAINOP16mo ago
was i supposed to put a breakpoint in the try/catch?
Denis
Denis16mo ago
To remove any third party influences
GIGA BRAIN
GIGA BRAINOP16mo ago
i ran the code and it finished executing and i got no exception errors
Denis
Denis16mo ago
You should place a breakpoint somewhere to halt the code Place them with F9 Step with F10 You can also click and drag the yellow arrow that appears to rerun code
GIGA BRAIN
GIGA BRAINOP16mo ago
man that's so weird i have two breakpoints and the program still finishes executing
GIGA BRAIN
GIGA BRAINOP16mo ago
Denis
Denis16mo ago
Best put on line 43 instead of 44 But yeah... It is weird
GIGA BRAIN
GIGA BRAINOP16mo ago
still the same gig
Denis
Denis16mo ago
Server running?
GIGA BRAIN
GIGA BRAINOP16mo ago
yup i think i might just look for a completed project similar to mine and see what they did i can't find how to consume a web api on youtube the documentation on microsoft doesn't seem applicable to my situation either i'm definitely missing something though lol
Denis
Denis16mo ago
Just find a webapi tutorial Nick Chapsas must have one
GIGA BRAIN
GIGA BRAINOP16mo ago
bet thanks i appreciate the help
Pobiega
Pobiega16mo ago
At a glance, Im guessing you are not awaiting showEntries when calling it from your menu code Also, your Helpers class isnt really a helper, its non static for one :p the above guess is based on the fact that your main entrypoint does... menu.ShowMenu();
GIGA BRAIN
GIGA BRAINOP16mo ago
i will look into this tomorrow my brain is absolutely fried ty for the input
Greg
Greg16mo ago
If it's not hitting the breakpoints you have in the screenshot, you may be missing an await on an async method somewhere.
Denis
Denis16mo ago
that is true, didn't occur to me
GIGA BRAIN
GIGA BRAINOP16mo ago
WOW THIS WAS IT what you said makes so much sense i for sure wasn't thinking my other method calls needed an await thank you my idea behind the helpers class is that it will ahve the methods that talk to the api i'm trying to follow srp can you explain what your idea of a helper class is
GIGA BRAIN
GIGA BRAINOP16mo ago
GIGA BRAIN
GIGA BRAINOP16mo ago
is it also normal to see an info log? is there any way to hide that
Pobiega
Pobiega16mo ago
yes first, async/await "bubbles" up if you dont await an async operation, its considered "fire and forget" and that means it does weird stuff, like you saw Well, seems more your "helper" class is actually a typed client if you ask me so just rename it and keep using it but "Helpers" is a bad name, and "{ApiNameHere}Client" is a better name 🙂
GIGA BRAIN
GIGA BRAINOP16mo ago
regarding typed and named clients, i thought what I had was leaning more towards a named client because i plan on having the post, put, and delete methods as well here but it seems that my client is only accessing a single endpoint so its more fitting as a typed client? and I was trying to implement the IHttpClientFactory dependency injection, but when i was reading the documentation for it the example for typed clients at least just used the regular httpclient. are they the same thing or am i just using it wrong?
GIGA BRAIN
GIGA BRAINOP16mo ago
Pobiega
Pobiega16mo ago
named clients is mostly for when all you need is a baseurl and some settings a typed client is its own type
GIGA BRAIN
GIGA BRAINOP16mo ago
thats what i'm referring to^
GIGA BRAIN
GIGA BRAINOP16mo ago
oooh i see i figured when it said many distinct uses that my case applied
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server