C
C#11mo 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 BRAIN11mo ago
Also is there any point in having asynchronous calls if this isn't a front end web app?
Denis
Denis11mo 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 BRAIN11mo ago
mm what server code would I add? it's a very basic basic api
Denis
Denis11mo ago
Or you can start the app manually and attach later with Shift+Alt+P
GIGA BRAIN
GIGA BRAIN11mo ago
i tried doing the run multiple apps in visual studio and it only ran the web api
Denis
Denis11mo 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 BRAIN11mo ago
BlazeBin - huazdopymmjt
A tool for sharing your source code with the world!
GIGA BRAIN
GIGA BRAIN11mo 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 BRAIN11mo ago
Denis
Denis11mo ago
And what actions can you select other than start?
GIGA BRAIN
GIGA BRAIN11mo ago
start without debugging or none
Denis
Denis11mo 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 BRAIN11mo 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
Denis11mo ago
The link is incorrect And via postman what url works for you?
GIGA BRAIN
GIGA BRAIN11mo ago
Denis
Denis11mo ago
Are you able to connect to the server?
GIGA BRAIN
GIGA BRAIN11mo ago
yeah
GIGA BRAIN
GIGA BRAIN11mo ago
Denis
Denis11mo ago
Weird
GIGA BRAIN
GIGA BRAIN11mo 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
Denis11mo 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 BRAIN11mo ago
yeah im running the server manually atm
Denis
Denis11mo ago
Maybe your client is crashing Or.not getting data in the expected format
GIGA BRAIN
GIGA BRAIN11mo ago
ok i see that my result is null
GIGA BRAIN
GIGA BRAIN11mo ago
GIGA BRAIN
GIGA BRAIN11mo 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
Denis11mo ago
You need to step to the next line, because result wants evaluated yet
GIGA BRAIN
GIGA BRAIN11mo 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
Denis11mo ago
Huh Wrap that in a try catch
GIGA BRAIN
GIGA BRAIN11mo ago
Denis
Denis11mo ago
Remember to add (Exception e) to the catch block Your server crashes too?
GIGA BRAIN
GIGA BRAIN11mo ago
server works completely fine still up gonna add the try catch now
Denis
Denis11mo 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 BRAIN11mo 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
Denis11mo ago
Maybe it is ina different format than your dto model
GIGA BRAIN
GIGA BRAIN11mo ago
does this look about right? my DTO model is the exact same as my regular model
Denis
Denis11mo ago
Yeah Try running
GIGA BRAIN
GIGA BRAIN11mo ago
does it make a difference if my web api is using a local sql server db?
Denis
Denis11mo ago
nope it shouldn't You could try and modify the server to return some test data
GIGA BRAIN
GIGA BRAIN11mo ago
was i supposed to put a breakpoint in the try/catch?
Denis
Denis11mo ago
To remove any third party influences
GIGA BRAIN
GIGA BRAIN11mo ago
i ran the code and it finished executing and i got no exception errors
Denis
Denis11mo 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 BRAIN11mo ago
man that's so weird i have two breakpoints and the program still finishes executing
GIGA BRAIN
GIGA BRAIN11mo ago
Denis
Denis11mo ago
Best put on line 43 instead of 44 But yeah... It is weird
GIGA BRAIN
GIGA BRAIN11mo ago
still the same gig
Denis
Denis11mo ago
Server running?
GIGA BRAIN
GIGA BRAIN11mo 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
Denis11mo ago
Just find a webapi tutorial Nick Chapsas must have one
GIGA BRAIN
GIGA BRAIN11mo ago
bet thanks i appreciate the help
Pobiega
Pobiega11mo 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 BRAIN11mo ago
i will look into this tomorrow my brain is absolutely fried ty for the input
Greg
Greg11mo 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
Denis11mo ago
that is true, didn't occur to me
GIGA BRAIN
GIGA BRAIN11mo 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 BRAIN11mo ago
GIGA BRAIN
GIGA BRAIN11mo ago
is it also normal to see an info log? is there any way to hide that
Pobiega
Pobiega11mo 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 BRAIN11mo 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 BRAIN11mo ago
Pobiega
Pobiega11mo 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 BRAIN11mo ago
thats what i'm referring to^
GIGA BRAIN
GIGA BRAIN11mo ago
oooh i see i figured when it said many distinct uses that my case applied
Accord
Accord11mo 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
More Posts