Tim. You're a Godsend. I recently spent a couple of hours writing classes for deserializing large json files. My heart sand when you pulled down the menu to convert json to classes. ! Now I have to write code to deal with multiple different devices with httpclient. I am not using DI , primarily because I don't fully understand it or how it applies to a C# WPF prog like I am developing. This was very helpful. I always love it when something I don't expect pops up in your vids. Thanks again.
Thanks! I want to create a project for hands-on, but was banging my head on stackoverflow and ms documentations, got this great resource, you are doing a great job.👍
Nice info. I think the next step would be to refactor the httpclient code out of the razor page into a weatherService class that does all that work, and inject the weatherService into the razor page to keep your layers and responsibilities de-coupled.
They were teaching us Ada & Fortran at USC back in the 80s when the industry was using C & Visual Basic! Thank god, I was working in the industry more than going to class back then. I'm a big believer of learning computer science and software development online instead of in schools.
@@mrcalico7091 Feels like it's now happening as the trend that will change the surface of an education methods dramatically. Those days when online courses have been looking just like the way to spend time are almost gone.
Great video, I managed to get my WebAssy app to call API working using this. Definitely had issues with CORS as you mentioned. Also need to see how to send with JWT auth. Also had issue getting config from the program.cs in the WebAssy app (no startup.cs). So I'll be looking forward to another video with a WebAssy app that covers all this. Thanks!
Hi Tim, Great Job! I just found your channel and will be a regular from now on. I see in some of the comments there was mention of a video showing how to POST data. Have you posted one of those yet?
To get properly named json to c# classes you can get them from quicktype.io/csharp/. Then just change the JsonProperty to JsonPropertyName, and add the System.Text.Json.Serialization reference. Thanks for the video Tim.
Ah, the joys of UA-cam when you search for how to call an old SOAP webservice in Blazor and you're a way into the suggested video before you realise that's not what's being explained at all and you've wasted time you don't have.
Bummer. You could probably take the new ways of talking to HttpClient from this video and combine it with the answer to this Stack Overflow question: stackoverflow.com/a/20108971/733798
I need to consume an endpoint that returns a JSON array (that is, the JSON text starts with a '['-character). Generating the model from JSON with "Paste Special" works fine. However, because the received JSON represents an array and not a single object, I think that "Paste Special" is doing it wrong when it generates a *single* Rootobject (with an array inside of it). And obviously it doesn't work either, because the *ReadFromJsonAsync()* throws an exception on the first JSON character it sees (the '['). Is there a trick that I can use to consume the JSON anyway?
I think I found the answer myself: Just disregard the genereted *RootObject* class and do a *ReadFromJasonAsync()* instead (where *Class1* is the generated type of the objects inside the JSON array)
@@martinchristiansen556 Thanks, this might fix the issue I'm having too. I was trying to pull in a JSON RootObject that contains a list of objects but I guess I just need to read directly into the list.
Hi Tim, at 6:48 you state that the meta weather api doesn't have CORS but I believe it does by using the x-frame-options header value of DENY. That is why it is rejected by the browser when running the HttpClient request from the Blazor webassembly client. Am I correct? The swapi.dev api site however does not have that issue.
It does not have a CORS issue that is stopping the call. I actually had an issue with SWAPI. I'll be doing a video on working with CORS soon, including how to get around it when you don't control the API.
@@IAmTimCorey wait, you don't have a CORS error when calling it from Blazor WebAssembly? Because that's the error I get. Or you set something that keeps it from being a problem? Blazor server doesn't have an issue as you can set it to use CORS to whitelist the API origin.
Would it be better in terms of clean architecture to have a separate service class that calls the api? or its it better off in the blazor component file itself
Hi Tim, would this method work for calling an API that is a completely separate app? From debugging the code I have noticed that my "client" is NULL therefore I believe my Blazor App is not finding the URI that is supplied! Tried several different techniques but to no avail. I have looked thru MS documentation, watched this video several times while taking notes and viewed videos from Nick Chapass /Raw Coding but neither are using separate apps. Any help from yourself or other pupils would be appreciated. Thanks.
Hello, i have my solution structured like Client -- Server -- Shared, I have to somehow access the HttpClient on my server project in my Client project to reach IHttpClientFactory, anyway to resolve this?
Those are separate projects. You cannot access a class instance across those projects. You will need to create a IHttpClientFactory on your client project as well, not just on your server project.
would be good , if you have some video on HttpClient(POST) , with some advanced concepts like sending IFormFile in post request , send parameters to post request
How do you deal with making API calls to a SQL Server instance hosted locally? I'm using EF Core and EF SQLServer and can get it to work locally when debugging, but for some reason get the 500 Server error when hosting it on IIS and accessing it through a client browser. Any thoughts?
I am not sure where in your configuration you have an issue, but something isn't set up right. Maybe your website needs to have the connection string updated. Maybe there is a permissions issue with the username and password in the connection string. Maybe the issue is somewhere else entirely.
WebAPI is the API itself (the project that sends data to anyone who calls it - swapi.dev is an API). HttpClient is the utility in C# to call an API and get the data.
Because the US is backwards. We cling to 32 degrees as freezing, 212 degrees as boiling, 5,280 feet in a mile,12 inches in a foot, etc. Doesn't that sound simpler? 😂
Thanks for the video, Tim. I would like to know how to configure the proxy server to consume the API through it. I'm getting Authentication error in the exception message ( Response status code does not indicate success: 407 (Proxy Authentication Required)). How do that with HttpClient?
Lets assume you have an WebAPI which references Services layer (class library) that handles all the logic. If you inject IHTTPClientFactory to the WebAPI all is fine, but how do you pass the HTTPClientFactory to the service layer so one is able to do calls from there? A class library doesn't know about IHTTPClientFactories and such.
It doesn't know about the API. It just knows that the JSON I am pasting needs to be turned into classes. It reads through the JSON structure and creates classes based upon the names and values in the pasted JSON.
@@IAmTimCorey Oh i understand now you highlighted all and then you pressed "paste json as class". Thanks Tim Corey this video is so helpful. Made me think already so many projects i can do with this.
The new System.Text.Json package is faster, so if you are able to use it and don't need the more advanced features of Newtonsoft, I would recommend going that way.
Thanks Tim. I wonder how would you overcome that underscore issue in a layered architecture where your DTO or a model would be a part of domain/core and api fetching service a part of Infrastructure layer? Since we can change weather api provider, there should be some mapping involved? Or am I looking at this from the wrong angle? I’d just prefer my models and DTOs to remain POCO.
I am not sure I see the issue. If your DTO needs to change based upon a higher layer, you would do a mapping to a new model. Does that answer your question?
@@IAmTimCorey Yeah, that's what I figured. What I wanted to ask, for an example in EF, you could decorate your entities, but if you prefer not to, you can specify decoration equivalents in the configuration. That way you can map things outside of the entities and have them remain completely oblivious of EF. IF you then switch to a different ORM, you just (hopefully) write new configuration specific to that ORM. Is there any way to do something similar with JSON deserialization using System.Net.Http.Json ? Hope this clears it up. Thanks, Tim.
Is there an elegant way of adding query string parameters to attach to the GET request, or is it best to build the full URL manually with something like stringbuilder?
Hi Tim, I have a very important question. The problem with IHttpclientFactory is that when used for a service like in blazor, it always creates a Transient, Service. But most of the time we want the service to be Scoped as an example to make it clearer. With Httpclient we write for a scoped service in program.cs of the client.WASM in NET6. builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddScoped(); which is scoped fine. But with IHttpclientFactory we would have builder.Services.AddHttpClient(client => { client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress); }); Which is transient which is not what we want! we want it scoped when injected in a component. How can we make this IHttpclientFactory create a scoped service here for (IProductService, ProductService)!!? The' easiest way possible?!! Thank you for your help.
You might need to stick with HttpClient for that (see the docs here: learn.microsoft.com/en-us/dotnet/core/extensions/httpclient-factory#httpclient-lifetime-management ). If that doesn't explain it well enough, you probably need to ask this question on Stack Overflow.
Great tutorial. How should I call the uri if I want to pass parameters? Should I add curly brackets after the uri with the dynamic parameters I need to pass?
It depends on what you mean. For the GET call, we are passing a parameter (the location ID). You just pass that as part of the string. If you are doing a POST command (or similar), you can pass the parameters separately in the call.
Great tutorial Tim. However how do I add httpclientfactory in a caliburn micro wpf bootstrapper.? The simple container singleton does not allow for the implementation of the client factory.
Tim, first of all thank you for all the great tutorials! My job schedule is very demanding but I am able to find 20 minutes here and 30 minutes there to follow them. Do you have an ordered index of all the videos? It would be great to go though them in the proper order, right now I am guessing from the names and upload dates.
What strategy do you suggest for clients generated by NSwag which is default for scaffolding REST API Clients in NET Framework in Visual Studio? It accepts HttpClient as an argument. Do you suggest creating one such client everytime (short lived, such as DbContext with EF Core) and populating it with a HttpClient received from IHttpClientFactory? The problem is that the NSwag-generated client accepting HttpClient in constructor does not implement IDisposable. How to work with that?
Hey Tim, Side question :) whats your theme on Visual Studio? looking to have the methods colored setup like yours where you have a clear diference between services.AddRazorPages();
Thanks tim i will watch this later tonight ,Blazor is amazing especially the client version the only thing bugging me is the CSS isolation hope they will add the feature soon, is it possible to share with us the course that you will publish next here on youtube or on your website ?
Hi! You say it will work in any .net core project type, but builder.Services.AddHttpClient(); isn't supported i Blazor webAssembly - so how to add IHttpClientFactory for wasm?
Can we consume an webapi in another webapi?? How can we create a request headers with basic authentication and client cert in consuming webapi request??
Sure. An API is just a C# application so it can do basically everything any other C# application can do behind the UI. So the calls would be no different than if we were making them from WPF or Blazor Server.
Tim, A lot of things have change with Webasembly especially in this area. I pretty sure this can be done ASP.Core Host server, it much more different related to HtmlClient. I want this work in something I am working - my quests it probably related to client is not actually a core project. When you research Webassembly, please research HtmlClient example here and with that project. One big difference there is no startup.cs
Base on Microsoft docs - I try the following replacement in program.cs string uri = "www.metaweather.com/api/"; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("app"); builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(uri)) .AddHttpMessageHandler(); builder.Services.AddTransient(sp => sp.GetRequiredService() .CreateClient("ServerAPI")); await builder.Build().RunAsync();
Maybe I missed it, but where is the OnInitializedAsync() coming from? I was wondering the same thing, and sure enough, it's underlined on my computer because it can't find the thing to override? Is this a Blazer/Razer only thing?
Awesome. Thanks for the video. Trying to find a proper way to use HttpClint for API call and here it is. Just wondering how come it has ""Loading" then "Table displayed" effect from that if else statement? Is that because the Async OnInitializedAsync method? what will be the experience if change it not to be Async?
It is not clear to me why you use System.Net.Http.Json instead of Microsoft.AspNet.WebApi.Client as you did in a previous video on api calls... What's the difference? Why use one instead than the other? Which one should we use?
Those are two different libraries. We are using Http.Json to handle translating the data from and to JSON. WebApi.Client does a lot more with connecting to the web. It isn't something we need in this instance.
How do you have a named client and also use a certificate? Without a factory, I would just create a HttpClientHandler and add the client certificate. Then add the handler to the client on creation. Additionally, how would you reset this client to a new certificate without restarting the app?
They are still wise. Remember that if a salt is exposed, your password is now only as strong as its complexity. A dictionary attack can be performed against just your password once the salt is acquired.
You would store it locally (appsetting, SQLite database, etc.) As for "safely" storing it, it depends on what you mean. If it is a client-side app (like this one is), the user will have access to the key no matter what. If you want to get around that, you will need to put the API call inside of your own API so that you can store the key on the server.
Would this be possible to run on Visual Studio 2017 by adding a global.json and setting the sdk version or is it pretty required to use Visual Studio 2019?
Last I heard, .NET Core 3.0 and beyond (and this is a .NET Core 3.1 project) is only supported on VSCode and Visual Studio 2019. I don't know your circumstances, but in most cases, you can get Visual Studio 2019 Community Edition for free. I would recommend going that route unless you are not allowed.
Hi Tim, I tried this except using the WebAssembly project and ran into CORS issues that I haven't been able to resolve. I'm not sure where the issue needs to be corrected. I ran the source linked above and it does work for me so it seems to be a webassembly specific issue.
I have one question about it. I saw that the httpclient was done directly in the blazor projects. However, most of the time, its actually done in a .net standard project. How does that work. Most times in the real world, you would use dependency injection to get weather data and would implement and hook into di. So the blazor side would not even know about httpclient since that is implemented in the .net standard library. How would that work. I actually tried to use ihttpclientfactory in the .net standard and it does not even show up. I would love to see something related to this but also show it in the .net standard with interfaces which allow you to swap so the blazor page would not even know about the httpclient.
Usually you would pass the HttpClientFactory into DI like I did, even if you have a .NET Standard library that depends on it. You would need to add a NuGet package in the library to bring in the IHttpClientFactory interface but that is all. I can add this to the suggestion list.
Hi Tim, When we use Multiple named http client, is there any way we can assign the common properties in single place instead repeating in all the named http clients? Thanks in advance
That Paste Special magic blew my mind!
Pretty cool, huh?
Ditto! Completely new to me.
Ikr, my jaw was dropped when I saw this.
I can't find it in VS for Mac?
This is still relevant in 2022. When I get stuck, I search for one of your videos on the topic. I like your approach.
Awesome!
This is my favorite kind of tutorial video. Focused, not too long, sample code. Thank you.
You are welcome.
15:50 "I don't think there's a weather icon"
oi-rain is perfect for it!
Thanks for sharing.
Tim. You're a Godsend. I recently spent a couple of hours writing classes for deserializing large json files. My heart sand when you pulled down the menu to convert json to classes. ! Now I have to write code to deal with multiple different devices with httpclient. I am not using DI , primarily because I don't fully understand it or how it applies to a C# WPF prog like I am developing. This was very helpful. I always love it when something I don't expect pops up in your vids. Thanks again.
I am glad it was helpful.
This is awesome tim. Just one example and you connected us to hundreds of API free for consumption such as spotify or twitter APIs.
I am glad it was helpful.
Thank you for great step by step lesson on HttpClient. I have used couple of time, but the one-liner trick is so great!
You're very welcome!
Thanks so much Tim, you have a way of explaining things that make it easy to understand and gives context. Much appreciated!
My pleasure!
Thanks!
Thank you!
Cool, finally some up-to-date Http client information. Thanks Corey.
You are welcome.
Thanks! I want to create a project for hands-on, but was banging my head on stackoverflow and ms documentations, got this great resource, you are doing a great job.👍
Glad it helped!
BTW, this is a truly valuable lesson. I really learned a lot about the theory as well as the nuts and bolts of getting it working. Thanks.
Glad it was helpful!
Another great video! Even as a relatively experienced dev, there's always something I'm learning from you. Very helpful.
Thank you!
Paste Special...and my mind was completely blown.
Great!
Thanks a lot! It was great how you went to complex way to simplest way for us to comprehend the whole concepts. I loved it!
You are welcome.
Thank you tim for the great content, past as json is really great 👍🏻
You are welcome.
Would be good to see how authorization would be applied to the API Client() as well e.g. Auth0
I will add it to the list. Thanks for the suggestion.
@@IAmTimCorey Thank Tim, I'm looking forward this topic.
I think it would be added after creating the client, that is at the point of usage.
Agree adding httpClient auth token handling would be great!
@@IAmTimCorey Would love to see this TIm
Loving the config file usage, good to know. Also, the one liner for a connection string is fantastic. Thanks again Tim
You are welcome.
Im staring to doing some research in blazor and you have been publish this video.
Great!
That was awesome, I am going to try to use this in some little app tests tonight!
Great!
Nice info. I think the next step would be to refactor the httpclient code out of the razor page into a weatherService class that does all that work, and inject the weatherService into the razor page to keep your layers and responsibilities de-coupled.
Yep, that would be ideal. Get the data access out of the UI for sure.
Im really wishing my university would have been teaching this stuff 4 years ago. MS VS is so nice.
It is a great IDE.
They were teaching us Ada & Fortran at USC back in the 80s when the industry was using C & Visual Basic! Thank god, I was working in the industry more than going to class back then. I'm a big believer of learning computer science and software development online instead of in schools.
@@mrcalico7091 Feels like it's now happening as the trend that will change the surface of an education methods dramatically. Those days when online courses have been looking just like the way to spend time are almost gone.
@@mrcalico7091 Not everyway is for everyone, one way or the other. ;)
Great as always! You can add to your list, a video about client/server WebSocket tutorial if you want!
I noted your recommendation by adding it to Tim's list of possible future topics, thanks.
Hi, this video was great. Really easy to follow and understand. Thank you.
You are welcome.
I have a technical interview next week, youre helping me so much! Thank you!
Awesome!
Great video Tim. You have always something else to teach. Tks
You are welcome.
I recently stumbled upon a library called Flurl which wrappes the HttpClient in a very neat little fluent API
Great!
Great video, I managed to get my WebAssy app to call API working using this. Definitely had issues with CORS as you mentioned. Also need to see how to send with JWT auth. Also had issue getting config from the program.cs in the WebAssy app (no startup.cs). So I'll be looking forward to another video with a WebAssy app that covers all this. Thanks!
Suggested topic noted and added to the list
Hi Tim, Great Job! I just found your channel and will be a regular from now on. I see in some of the comments there was mention of a video showing how to POST data. Have you posted one of those yet?
Great video Tim. You should go further and do a video on typed HttpClients and maybe the use of a HttpClientHandler with it.
Thanks for the suggestion, added to the list.
AS always, understandable and lovely video!
Thanks!
To get properly named json to c# classes you can get them from quicktype.io/csharp/. Then just change the JsonProperty to JsonPropertyName, and add the System.Text.Json.Serialization reference. Thanks for the video Tim.
Thanks for sharing.
Thank you so much sir! That was very important thing to know.
As allways. Very well explained 👌 Thank you!
You are welcome.
Wow I didn't know that paste json classes its pretty useful for third party api
Yeah, that's a nice feature.
Hi Tim. Thanks for the tutorial!
You are welcome.
Ah, the joys of UA-cam when you search for how to call an old SOAP webservice in Blazor and you're a way into the suggested video before you realise that's not what's being explained at all and you've wasted time you don't have.
Bummer. You could probably take the new ways of talking to HttpClient from this video and combine it with the answer to this Stack Overflow question: stackoverflow.com/a/20108971/733798
I need to consume an endpoint that returns a JSON array (that is, the JSON text starts with a '['-character). Generating the model from JSON with "Paste Special" works fine. However, because the received JSON represents an array and not a single object, I think that "Paste Special" is doing it wrong when it generates a *single* Rootobject (with an array inside of it). And obviously it doesn't work either, because the *ReadFromJsonAsync()* throws an exception on the first JSON character it sees (the '['). Is there a trick that I can use to consume the JSON anyway?
I think I found the answer myself: Just disregard the genereted *RootObject* class and do a *ReadFromJasonAsync()* instead (where *Class1* is the generated type of the objects inside the JSON array)
Since it is sending back an array, you just ask for an array of the RootObject, yes.
@@martinchristiansen556 Thanks, this might fix the issue I'm having too. I was trying to pull in a JSON RootObject that contains a list of objects but I guess I just need to read directly into the list.
Hi Tim, at 6:48 you state that the meta weather api doesn't have CORS but I believe it does by using the x-frame-options header value of DENY. That is why it is rejected by the browser when running the HttpClient request from the Blazor webassembly client. Am I correct?
The swapi.dev api site however does not have that issue.
It does not have a CORS issue that is stopping the call. I actually had an issue with SWAPI. I'll be doing a video on working with CORS soon, including how to get around it when you don't control the API.
@@IAmTimCorey wait, you don't have a CORS error when calling it from Blazor WebAssembly? Because that's the error I get. Or you set something that keeps it from being a problem? Blazor server doesn't have an issue as you can set it to use CORS to whitelist the API origin.
Would it be better in terms of clean architecture to have a separate service class that calls the api? or its it better off in the blazor component file itself
Yes, if the app has any size at all, you should move the API calls out into the data access layer.
@@IAmTimCorey Thank you for the advice, always watching your videos and your great content!
Hi Tim, would this method work for calling an API that is a completely separate app? From debugging the code I have noticed that my "client" is NULL therefore I believe my Blazor App is not finding the URI that is supplied! Tried several different techniques but to no avail.
I have looked thru MS documentation, watched this video several times while taking notes and viewed videos from Nick Chapass /Raw Coding but neither are using separate apps. Any help from yourself or other pupils would be appreciated. Thanks.
Can you extract the api call and model creation into a service class to clean up this code and make it more reusable?
Thank you it helped me. Appreciate your contributions.
You are welcome.
Hello, i have my solution structured like Client -- Server -- Shared, I have to somehow access the HttpClient on my server project in my Client project to reach IHttpClientFactory, anyway to resolve this?
Those are separate projects. You cannot access a class instance across those projects. You will need to create a IHttpClientFactory on your client project as well, not just on your server project.
@@IAmTimCorey Awesome, thanks!
would be good , if you have some video on HttpClient(POST) , with some advanced concepts
like sending IFormFile in post request , send parameters to post request
I will add it to the list. Thanks for the suggestion.
How do you deal with making API calls to a SQL Server instance hosted locally? I'm using EF Core and EF SQLServer and can get it to work locally when debugging, but for some reason get the 500 Server error when hosting it on IIS and accessing it through a client browser. Any thoughts?
I am not sure where in your configuration you have an issue, but something isn't set up right. Maybe your website needs to have the connection string updated. Maybe there is a permissions issue with the username and password in the connection string. Maybe the issue is somewhere else entirely.
Hi Corey! Could you do this tutorial on Blazor Web Assembly? How would this differ?
I can add that to the suggestion list.
Thank you for this amazing guide, do you know by any chance how to send a GET request to a blazor page and capture it?
I wonder what is the difference between WebApi and HttpClient as you have two different videos with different setup. Thank you.
WebAPI is the API itself (the project that sends data to anyone who calls it - swapi.dev is an API). HttpClient is the utility in C# to call an API and get the data.
Awesome video, as always. The only thing I do not get, is why you would want to convert Celsius to Fahrenheit 🤔
Because the US is backwards. We cling to 32 degrees as freezing, 212 degrees as boiling, 5,280 feet in a mile,12 inches in a foot, etc. Doesn't that sound simpler? 😂
Very useful content. Thank you for your sharing.
You are welcome.
Great tutorial. Keep up the good work👍
Thanks!
Thanks for the video, Tim. I would like to know how to configure the proxy server to consume the API through it. I'm getting Authentication error in the exception message ( Response status code does not indicate success: 407 (Proxy Authentication Required)). How do that with HttpClient?
I don't have a video on that but I'll add it to the suggestion list.
Lets assume you have an WebAPI which references Services layer (class library) that handles all the logic. If you inject IHTTPClientFactory to the WebAPI all is fine, but how do you pass the HTTPClientFactory to the service layer so one is able to do calls from there? A class library doesn't know about IHTTPClientFactories and such.
It is a NuGet package to add the ability to use IHTTPClientFactory.
I have a question. How paste json as class knows this api you showed us in 7:28 ?
It doesn't know about the API. It just knows that the JSON I am pasting needs to be turned into classes. It reads through the JSON structure and creates classes based upon the names and values in the pasted JSON.
@@IAmTimCorey Oh i understand now you highlighted all and then you pressed "paste json as class".
Thanks Tim Corey this video is so helpful. Made me think already so many projects i can do with this.
Hi Tim, great video, thank you!
What do you think about using the Nuget package Newtonsoft.Json in the .net core project?
The new System.Text.Json package is faster, so if you are able to use it and don't need the more advanced features of Newtonsoft, I would recommend going that way.
Thank you, Tim.
Where can I see the features of System.Text.Json?
Excellent explanation.
Thank you very much
You are welcome.
any ideas how can i mock the library to unit test my code ?
I recommend a couple of my videos for this - ua-cam.com/video/DwbYxP-etMY/v-deo.html and ua-cam.com/video/ub3P8c87cwk/v-deo.html
Thanks Tim. I wonder how would you overcome that underscore issue in a layered architecture where your DTO or a model would be a part of domain/core and api fetching service a part of Infrastructure layer? Since we can change weather api provider, there should be some mapping involved? Or am I looking at this from the wrong angle? I’d just prefer my models and DTOs to remain POCO.
I am not sure I see the issue. If your DTO needs to change based upon a higher layer, you would do a mapping to a new model. Does that answer your question?
@@IAmTimCorey Yeah, that's what I figured. What I wanted to ask, for an example in EF, you could decorate your entities, but if you prefer not to, you can specify decoration equivalents in the configuration. That way you can map things outside of the entities and have them remain completely oblivious of EF. IF you then switch to a different ORM, you just (hopefully) write new configuration specific to that ORM. Is there any way to do something similar with JSON deserialization using System.Net.Http.Json ? Hope this clears it up. Thanks, Tim.
Is there an elegant way of adding query string parameters to attach to the GET request, or is it best to build the full URL manually with something like stringbuilder?
Probably the easiest is just appending the parameters. No need for even stringbuilder since you aren't doing it repetitively.
Great help! I could mind a video on api with auth and sending bodies etc. Also some SignalR would be useful. Thanks Tim :)
I will add it to the list. Thanks for the suggestion.
Great video, thanks for sharing!
You are welcome.
I noticed you didn't dispose the HttpRequestMessage or HttpResponseMessage. Was that intentional? Is there no benefit or drawback in doing so or not?
Correct. They get disposed of like any other object in C#.
@@IAmTimCorey Sure. But they implement IDisposable. So, just confused how a person knows when and when not to declare them with a using statement.
@@Ristogod Pretty sure you should be using a using statement. But hey I'm no professional
Great tutorial! Could you share how you would decorate a C# property to change it to a C# naming convention?
I will add it to the list. Thanks for the suggestion.
Hi Tim,
I have a very important question. The problem with IHttpclientFactory is that when used for a service like in blazor, it always creates a Transient, Service. But most of the time we want the service to be Scoped as an example to make it clearer. With Httpclient we write for a scoped service
in program.cs of the client.WASM in NET6.
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped();
which is scoped fine. But with IHttpclientFactory we would have
builder.Services.AddHttpClient(client =>
{
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
});
Which is transient which is not what we want! we want it scoped when injected in a component. How can we make this IHttpclientFactory create a scoped service here for (IProductService, ProductService)!!? The' easiest way possible?!!
Thank you for your help.
You might need to stick with HttpClient for that (see the docs here: learn.microsoft.com/en-us/dotnet/core/extensions/httpclient-factory#httpclient-lifetime-management ). If that doesn't explain it well enough, you probably need to ask this question on Stack Overflow.
Great tutorial. How should I call the uri if I want to pass parameters? Should I add curly brackets after the uri with the dynamic parameters I need to pass?
It depends on what you mean. For the GET call, we are passing a parameter (the location ID). You just pass that as part of the string. If you are doing a POST command (or similar), you can pass the parameters separately in the call.
Wove great. Can you please create a training session on creating a api gateway in .net core?
I will add it to the list. Thanks for the suggestion.
Great example, I liked new razor.
Thanks!
Is there any difference in terms of performance when using try catch?
Try/catch does add overhead but unless you are making hundreds of repeated calls per client, it should not be noticeable. Good question.
Is there any idea to without change in web api & only change in wasm to allow cors.
this was very helpful. Thanks for sharing
Glad it was helpful!
Great tutorial Tim. However how do I add httpclientfactory in a caliburn micro wpf bootstrapper.? The simple container singleton does not allow for the implementation of the client factory.
Great video! You are awesome, thank you ,Tim
Thank you!
Tim, first of all thank you for all the great tutorials! My job schedule is very demanding but I am able to find 20 minutes here and 30 minutes there to follow them. Do you have an ordered index of all the videos? It would be great to go though them in the proper order, right now I am guessing from the names and upload dates.
What strategy do you suggest for clients generated by NSwag which is default for scaffolding REST API Clients in NET Framework in Visual Studio? It accepts HttpClient as an argument. Do you suggest creating one such client everytime (short lived, such as DbContext with EF Core) and populating it with a HttpClient received from IHttpClientFactory?
The problem is that the NSwag-generated client accepting HttpClient in constructor does not implement IDisposable. How to work with that?
im assuming a razor page is the equivalent of a combination of a Controller and Webpage from a ASP.NET Core w/ React app?
Great video, Tim! Thanks a lot
Thank you!
Thank you so much, this is really useful
You are welcome.
A very informative video. Thank you!
You are welcome.
Hey Tim,
Side question :) whats your theme on Visual Studio? looking to have the methods colored setup like yours where you have a clear diference between services.AddRazorPages();
I just use the standard Dark theme in VS2019.
Thanks tim i will watch this later tonight ,Blazor is amazing especially the client version the only thing bugging me is the CSS isolation hope they will add the feature soon,
is it possible to share with us the course that you will publish next here on youtube or on your website ?
This would be really helpful, knowing you have already said in road map video still want to know what will be as free content on youtube
I don't have a public roadmap to share at this point but I'm hoping to make some announcements in the next few weeks.
Thank you friend! You the best!
You are welcome.
Hi! You say it will work in any .net core project type, but builder.Services.AddHttpClient(); isn't supported i Blazor webAssembly - so how to add IHttpClientFactory for wasm?
Check out my video on Blazor WebAssembly. I show how HttpClient is set up. There is already one set up in the project when you create a new project.
@@IAmTimCorey If you meant your newest video, it didn't mention anything about IHttpClientFactory for wasm?
Can we consume an webapi in another webapi?? How can we create a request headers with basic authentication and client cert in consuming webapi request??
Sure. An API is just a C# application so it can do basically everything any other C# application can do behind the UI. So the calls would be no different than if we were making them from WPF or Blazor Server.
Take a shot every time Tim spins his mouse cursor around in circles.
I’m getting a display I can stand in front of to solve this type of problem.
@@IAmTimCorey I'm going to miss getting bombed watching your videos.
Tim, A lot of things have change with Webasembly especially in this area. I pretty sure this can be done ASP.Core Host server, it much more different related to HtmlClient. I want this work in something I am working - my quests it probably related to client is not actually a core project. When you research Webassembly, please research HtmlClient example here and with that project. One big difference there is no startup.cs
Base on Microsoft docs - I try the following replacement in program.cs
string uri = "www.metaweather.com/api/";
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("app");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddHttpClient("ServerAPI",
client => client.BaseAddress = new Uri(uri))
.AddHttpMessageHandler();
builder.Services.AddTransient(sp => sp.GetRequiredService()
.CreateClient("ServerAPI"));
await builder.Build().RunAsync();
I will be showing how to do this in Blazor WebAssembly shortly.
Maybe I missed it, but where is the OnInitializedAsync() coming from? I was wondering the same thing, and sure enough, it's underlined on my computer because it can't find the thing to override? Is this a Blazer/Razer only thing?
Correct, that is from the Blazor base class.
Awesome. Thanks for the video. Trying to find a proper way to use HttpClint for API call and here it is. Just wondering how come it has ""Loading" then "Table displayed" effect from that if else statement? Is that because the Async OnInitializedAsync method? what will be the experience if change it not to be Async?
Yes, the page renders before the async call is made. It would not change that part of the experience if you made the call a blocking call.
It is not clear to me why you use System.Net.Http.Json instead of Microsoft.AspNet.WebApi.Client as you did in a previous video on api calls... What's the difference? Why use one instead than the other? Which one should we use?
Those are two different libraries. We are using Http.Json to handle translating the data from and to JSON. WebApi.Client does a lot more with connecting to the web. It isn't something we need in this instance.
Great content. Can I get the API config from a data base and kind of "inject" in startup class? Thank You.
How do you have a named client and also use a certificate? Without a factory, I would just create a HttpClientHandler and add the client certificate. Then add the handler to the client on creation. Additionally, how would you reset this client to a new certificate without restarting the app?
Are complex passwords really needed when they are being stored as salted hashes in the backend?
They are still wise. Remember that if a salt is exposed, your password is now only as strong as its complexity. A dictionary attack can be performed against just your password once the salt is acquired.
@@IAmTimCorey a lot of websites have these complexity meters for passwords. How do those work?
Can you go over how to add basic authentication to the client ?
ua-cam.com/video/9QU_y7-VsC8/v-deo.html - check this out
Hello, I was wondering how to make an input field to make the location variable. I know it's not practical in this case, but as an example
Very nice video thank you, I just wished you had gone further to post and bearer authentication
I do that in the TimCo Retail Manager course here on UA-cam, if you are interested.
If this api required an api key, where would I safely store it and how would I access it in the url when making my GET request?
You would store it locally (appsetting, SQLite database, etc.) As for "safely" storing it, it depends on what you mean. If it is a client-side app (like this one is), the user will have access to the key no matter what. If you want to get around that, you will need to put the API call inside of your own API so that you can store the key on the server.
Hey Tim you have been great thank you.
You are welcome.
Would this be possible to run on Visual Studio 2017 by adding a global.json and setting the sdk version or is it pretty required to use Visual Studio 2019?
Last I heard, .NET Core 3.0 and beyond (and this is a .NET Core 3.1 project) is only supported on VSCode and Visual Studio 2019. I don't know your circumstances, but in most cases, you can get Visual Studio 2019 Community Edition for free. I would recommend going that route unless you are not allowed.
@@IAmTimCorey that's what I was thinking you, just wanted to check with you!
Hi Tim, I tried this except using the WebAssembly project and ran into CORS issues that I haven't been able to resolve. I'm not sure where the issue needs to be corrected. I ran the source linked above and it does work for me so it seems to be a webassembly specific issue.
I'm going to be covering how to work with CORS very soon.
IAmTimCorey please do it in the context of web assembly as it is fairly well covered for server.
I have one question about it. I saw that the httpclient was done directly in the blazor projects. However, most of the time, its actually done in a .net standard project. How does that work. Most times in the real world, you would use dependency injection to get weather data and would implement and hook into di. So the blazor side would not even know about httpclient since that is implemented in the .net standard library. How would that work. I actually tried to use ihttpclientfactory in the .net standard and it does not even show up. I would love to see something related to this but also show it in the .net standard with interfaces which allow you to swap so the blazor page would not even know about the httpclient.
Usually you would pass the HttpClientFactory into DI like I did, even if you have a .NET Standard library that depends on it. You would need to add a NuGet package in the library to bring in the IHttpClientFactory interface but that is all. I can add this to the suggestion list.
Hi Tim, When we use Multiple named http client, is there any way we can assign the common properties in single place instead repeating in all the named http clients? Thanks in advance