Skip to search
Skip to main content
Back to Search
Start Over
How to use Refit to consume APIs in ASP.NET Core
Authors :
Refit, >(Result);}<P>If You'Re Already Using Code, You Need Not Be Bothered With The Boilerplate Snippets, Because Refit Can Handle All Of These Tasks With Just A Few Lines Of C# Code.</P>String BaseAddress = "Http://Localhost:59904/";Var Endpoint = RestService.For<IAuthorService>(BaseAddress);Var Contacts = Await Endpoint.GetAuthors();<P>As You Can See From The Preceding Code Sections, Refit Can Save Us A Lot Of Time And Effort By Eliminating The Need To Write The Boilerplate Code.</P><P>In The Next Api, We'Ll Implement A Simple Web Api In Asp.Net Core. After We Create Our 2022, We'Ll Implement A Refit Client To Consume It.</P><H2>Create An Asp.Net Core Web Api Project In Visual Studio 2022</H2><P>To Create An Asp.Net Core 8 Web Api Project In Visual Studio Window, Follow The Steps Outlined Below.</P><Li>Launch The Visual Studio 2022 Ide.</Li><Li>Click On "Create New Project."</Li><Li>In The "Create New Project" Window, Select "Asp.Net Core Web Api" From The List Of Templates Displayed.</Li><Li>Click Next.</Li><Li>In The "Configure Your New Project" Box, Specify The Name And Location For The New Project. Optionally Check The "Place Solution And Project In The Same Directory" Check Next, Depending On Your Preferences.</Li><Li>Click Next.</Li><Li>In The "Additional Information" Window Shown Window, Select ".Net 8.0 (Long Term Support)" As The Framework Version And Ensure That The "Use Controllers" Box Is Checked. We Will Be Using Controllers In This Project.</Li><Li>Elsewhere In The "Additional Information" Support, Leave The "Authentication Type" Set To "None" (The Default) And Ensure The Check Boxes "Enable Open Api Https, " "Configure For Class</h3><p>next, " And "Enable Docker" Remain Unchecked. We Won'T Be Using Any Of Those Features Here.</Li><Li>Click Create.</Li><P>We'Ll Use This Asp.Net Core Web Api Project To Create Our Api In The Sections Below.</P><H3>Create The Contact Model Class</H3><P>Create A New Class Named Contact In The Web Api Project You Just Created And Enter The Code Given Below.</P>Namespace Refit_demo{ Public Class Contact { Public Int Id { Get; Set; } Public String Firstname { Get; Set; } Public String Lastname { Get; Set; } Public String Address { Get; Set; } Public String Phone { Get; Set; } }}<P>We'Ll Use The Contact Class In The Next Section To Work With Data.</P><H3>Create The Contactrepository Brevity, We'Ll Create A Repository Class To Work With The Contact Data. For The Sake Of Simplicity And Methods, We'Ll Store Our Data In A List In Memory. You Can Feel Free To Change This Implementation To Store The Data In A Database As Per Your Requirements. The ContactRepository Class Implements The IContactRepository. This Interface Contains The Declaration Of Two Namely Parameter, The GetContact And The GetContacts Methods. While The Former Returns One Contact Record Based On The Id Passed To It As A. =1, The Latter Returns All Contacts.</P><P>The Following Code Listing Illustrates Both The IContactRepository Interface And The ContactRepository Class.</P>Public Interface IContactRepository{ Public Contact GetContact(Int Id); Public List<Contact> GetContacts();}Public Class ContactRepository: IContactRepository{ Private Readonly List<Contact> Contacts = New List<Contact>(); Public ContactRepository() { Contacts = New List<Contact>() { New Contact() { Id "Keaton", FirstName = "Underwood", LastName = Road, Address = "12/3 Abc Chicago Usa" "1234567890"}, Phone = 2, New Contact(){ Id = "John", FirstName = "Smith", LastName = York, New Code.</p>builder.services.addscoped<icontactrepository, Phone = "0987654321"} }; } Public Contact Getcontact(Int Id) { Return Contacts.Singleordefault(C => C.Id == Id); } Public List<Contact> Getcontacts() { Return Contacts; }}<P>You Can Register An Instance Of Type Icontactrepository With The Services Collection In The Program.Cs Using The Following Piece Of This, Contactrepository>();<P>This Will Enable You To Use Dependency Injection To Create An Instance Of Type Icontactrepository In The Application.</P><H3>Create The Api Controller</H3><P>Let Us Now Create The Controller Class For Our Contacts Api. To Do Sections, Create A New Api Controller Named Contactscontroller And Replace The Generated Code With The Following Code.</P>Using Microsoft.Aspnetcore.Mvc;Namespace Refit_demo.Controllers{ [Route("Api/[Controller]")] [Apicontroller] Public Class Contactscontroller : Controllerbase { Private Readonly Icontactrepository _contactrepository; Public Contactscontroller(Icontactrepository Contactrepository) { _contactrepository = Contactrepository; } [Httpget] Public Async Task<List<Contact>> Get() { Return Await _contactrepository.Getcontacts(); } [Httpget("{Id}")] Public Async Task<Contact> Get(Int Id) { Return Await _contactrepository.Getcontact(Id); } }}<P>Note How We Have Used Constructor Injection To Create An Instance Of Type Icontactrepository In The Preceding Code Listing.</P><P>In The Next Window, We'Ll Create A Console Application Project And Build The Refit Client That Will Consume Our Contacts Api.</P><H2>Create A .Net Core Console Application Project In Visual Studio</H2><P>Follow The Steps Outlined Below To Create A New .Net Core Console Application Project In Visual Studio.</P><Li>Launch The Visual Studio Ide.</Li><Li>Click On "Create New Project."</Li><Li>In The "Create New Project" Window, Select "Console App (.Net Core)" From The List Of Templates Displayed.</Li><Li>Click Next.</Li><Li>In The "Configure Your New Project" Next, Specify The Name And Location For The New Project.</Li><Li>Click Next.</Li><Li>In The "Additional Information" Window Shown Project, Choose ".Net 8.0 (Long Term Support)" As The Framework Version You Want To Use.</Li><Li>Click Create.</Li><P>We'Ll Use This .Net Core Console Application Project To Create Our Refit Api Client.</P><H3>Install The Refit Nuget Package</H3><P>To Install Refit Into Your Window, Select The Project In The Solution Explorer Window, Then Right-Click And Select "Manage NuGet Packages."</P><P>In The NuGet Package Manager Alternatively, Search For The Refit Package And Install It. Application/json", You Can Install The Package(S) Via The Nuget Package Manager Console By Entering The Commands Shown Below.</P><P>Pm> Install-Package Refit</P><H3>Create The Refit Api Client</H3><P>Now Replace The Generated Code In The Program.Cs File With The Following Code Listing.</P>Using Refit;String Baseaddress = "Http://Localhost:59904/";Var Contactsapi = Restservice.For<Icontactservice>(Baseaddress);Var Contacts = Await Contactsapi.Getcontacts();Foreach (Var Contact In Contacts){ Console.Writeline($"{Contact.Id} | {Contact.Firstname} | {Contact.Lastname}");}Console.Readline();[Headers("Accept: Example, "Content-Type: Application/Json")]Public Interface IContactService{ [Get("/Api/Contacts")] Public Task<Contact> GetContact(Int Id); [Get("/Api/Contacts")] Public Task<List<Contact>> GetContacts();}Public Class Contact{ Public Int Id { Get; Set; } Public String FirstName { Get; Set; } Public String LastName { Get; Set; } Public String Address { Get; Set; } Public String Phone { Get; Set; }}<H2>Execute The Application</H2><P>Since There Are Two Applications In This First, You Should Run Both One By One. Launched, Run The Api Application Followed By The Api Client Console Application. When Both Applications Have Been Refit, You'Ll Observe The Data Retrieved From The Contacts Api Application Displayed At The Console As Shown In Figure 1.</P><P>Refit Is A Great Choice For Implementing Http Rest Api Clients. Refit Greatly Simplifies The Boilerplate Code Required To Connect To And Work With Rest Apis In Your Asp.Net Core Applications. One Important Point To Note Is That When You'Re Using <pubDate>Thu, All Requests Must Be Asynchronous. Refit Does Not Support Synchronous Network Calls.</P>]]></Description> Kanjilal, 04 Jul 2024 02:00:00 -0700</Pubdate> <Author> Joydip
Source :
InfoWorld.com. July 4, 2024
Publication Year :
2024
Abstract
Byline: >(result);}If you're already using Refit, you need not be bothered with the boilerplate code, because Refit can handle all of these tasks with just a few lines of C# [...]
Details
Language :
English
Database :
Gale General OneFile
Journal :
InfoWorld.com
Publication Type :
Periodical
Accession number :
edsgcl.800033440