Consuming ASP. NET Core 2. Web API using Http. Client. Problem. In this post, you will see how to consume ASP. NET Core Web API using Http. Client. Solution. We’ll create a library to wrap the functionality of Http. Client. I’ll use builder pattern for this purpose. Add a class with methods for storing parts of Http. The latest news about Opera web browsers, tech trends, internet tips. Client: publicclass Http. Request. Builder. Http. Method method = null. Uri = "". private Http. Content content = null. Token = "". privatestring accept. Header = "application/json". Time. Span timeout = new Time. Span(0, 0, 1. 5). Http. Request. Builder(). If you haven’t heard about Nodal yet, or you have but you’re unsure of where to begin, this tutorial is for you! Make sure you keep up with Nodal on GitHub to. Jar File Download examples (example source code) Organized by topic. Jar File Download; a /. ![]() Http. Request. Builder Add. Method(Http. Method method). Http. Request. Builder Add. Request. Uri(string request. This module extends the entity API of Drupal core in order to provide a unified way to deal with entities and their properties. Additionally, it provides an entity.Uri). this. request. Uri = request. Uri. Http. Request. Builder Add. Content(Http. Content content). Http. Request. Builder Add. Bearer. Token(string bearer. Token). this. bearer. Token = bearer. Token. Http. Request. Builder Add. Accept. Header(string accept. Header). this. accept. Header = accept. Header. Http. Request. Builder Add. Timeout(Time. Span timeout). Add a method to send request using Http. Client and return the response: publicasync Task< Http. Response. Message> Send. Async(). Ensure. Arguments(). Http. Request. Message. Method = this. method. Request. Uri = new Uri(this. Uri). if (this. content != null). Content = this. content. Is. Null. Or. Empty(this. Token)). request. Headers. Authorization =. Authentication. Header. Value("Bearer", this. Token). request. Headers. Accept. Clear(). if (! Is. Null. Or. Empty(this. Header)). request. Headers. Accept. Add(. Media. Type. With. Quality. Header. Value(this. Header)). var client = new System. Net. Http. Http. Client(). Timeout = this. timeout. Send. Async(request). We’ll also add a factory class to build requests for GET, POST, PUT, PATCH and DELETE: publicstaticclass Http. Request. Factory. Task< Http. Response. Message> Get(string request. Uri). var builder = new Http. Request. Builder(). Add. Method(Http. Method. Get). . Add. Request. Uri(request. Uri). returnawait builder. Send. Async(). publicstaticasync Task< Http. Response. Message> Post(. Uri, objectvalue). Http. Request. Builder(). Add. Method(Http. Method. Post). . Add. Request. Uri(request. Uri). . Add. Content(new Json. Content(value)) . Send. Async(). publicstaticasync Task< Http. Response. Message> Put(. Uri, objectvalue). Http. Request. Builder(). Add. Method(Http. Method. Put). . Add. Request. Uri(request. Uri). . Add. Content(new Json. Content(value)). returnawait builder. Send. Async(). publicstaticasync Task< Http. Response. Message> Patch(. Uri, objectvalue). Http. Request. Builder(). Add. Method(new Http. Method("PATCH")). Add. Request. Uri(request. Uri). . Add. Content(new Patch. Content(value)). returnawait builder. Send. Async(). publicstaticasync Task< Http. Response. Message> Delete(string request. Uri). var builder = new Http. Request. Builder(). Add. Method(Http. Method. Delete). . Add. Request. Uri(request. Uri). returnawait builder. Send. Async(). }Json. Content, Patch. Content and File. Content are custom classes to simplify sending of data: publicclass Json. Content : String. Content. public Json. Content(objectvalue). Json. Convert. Serialize. Object(value), Encoding. UTF8. "application/json"). Json. Content(objectvalue, string media. Type). : base(Json. Convert. Serialize. Object(value), Encoding. UTF8, media. Type). Patch. Content : String. Content. public Patch. Content(objectvalue). Json. Convert. Serialize. Object(value), Encoding. UTF8. "application/json- patch+json"). File. Content : Multipart. Form. Data. Content. File. Content(string file. Path, string api. Param. Name). var filestream = File. Open(file. Path, File. Mode. Open). var filename = Path. Get. File. Name(file. Path). Add(new Stream. Content(filestream), api. Param. Name, filename). Finally, few extension methods to help working with Http. Response. Message class: publicstaticclass Http. Response. Extensions. T Content. As. Type< T> (this Http. Response. Message response). Content. Read. As. String. Async(). Result. Is. Null. Or. Empty(data) ? T) . Json. Convert. Deserialize. Object< T> (data). Content. As. Json(this Http. Response. Message response). Content. Read. As. String. Async(). Result. Json. Convert. Serialize. Object(data). publicstaticstring Content. As. String(this Http. Response. Message response). Content. Read. As. String. Async(). Result. We can use the code above like: privatestaticasync Task Get. List(). var request. Uri = $"{base. Uri}". Http. Request. Factory. Get(request. Uri). Console. Write. Line($"Status: {response. Status. Code}"). var output. Model = response. Content. As. Type< List< Movie. Output. Model> > (). Model. For. Each(item =>. Console. Write. Line("{0} - {1}", item. Id, item. Title)). Here is how the sample client looks like: Note: Sample code has examples of other type of requests too. Note: Sample code uses CRUD API created in a previous post. Download its project and run the API before running this console sample. Angular. 2 in ASP. NET MVC & Web API - Part 1. Content. Part 1: Angular. Setup in Visual Studio 2. Basic CRUD application, third party modal pop up control. Part 2: Filter/Search using Angular. Global Error handling, Debugging Client side. Part 3: Angular 2 to Angular 4 with Angular Material Components. Part 4: Angular 4 Data Grid with Export to Excel, Sorting and Filtering. Introduction. Since Angular. I will try to explain the step by step guide to create basic CRUD (create, read, update and delete) application using Angular. MVC Web API as backend RESTful APIs. I will create blank ASP. NET MVC application, setup the Angular. User Management page where data will be loaded from SQL Server Database and user would have options to Add new user, Update and Delete existing user. For all database operation, Anguar. RESTful APIs that we will be developing using ASP. NET MVC Web API. This is a beginner level article and aimed to be written for novice developers and student who have basic knowledge of programming and want to start learning Angular. C# and RESTful APIs from scratch. If you are experienced developer and only need an overview, you can just download the attached project and go through it. You need Visual Studio and SQL Server Management Studio to develop the project along the article and compile the attached project. Download the Visual Studio 2. Community and SQL Server Management Studio. Let's Start. Setup Angular. Environment. Open Visual Studio, I am using Visual Studio 2. Community, you can use Visual Studio 2. Community with Update 3 installed for Node. Type. Script packages. Visual Studio 2. 01. Go to File menu and select File - > New - > Project: Enter the Project Name and select your desired . Net Framework (I am using . Net Framework 4. 6 for this article). Click on OK button: Select MVC from next screen and check Web API in Add folders and core reference options since we will create RESTful APIs for CRUD operations. Click on OK button: The basic ASP. NET MVC project is created, the next step is to prepare it for Angular. Let's do it next steps. Right click on Project Angular. MVC and select Add - > New Item: Enter package. Configuration File would be filtered. Click on Add button to add package. We will use NPM (Node Package Manager) configuration file to manage all Angular. To read more about NPM, check this link. Next, copy the Package. Angular. 2 Quick Start Git. Hub link and paste it in newly added package. Angular. 2MVC project: In dependencies section of package. Angular. 2 related packages, check here to see what is difference between ^ and ~ sign. Right click on package. Restore Packages, Visual Studio Node. Dev. Depnedencies section and restore it, it really makes the life easier: You would find new folder node_modules added in project that have all the downloaded packages: The next step to let our project know how to get these packages, we will add systemjs. Right click on Angular. MVC project and select Add - > Java. Script file: Enter the name systemjs. Item name field and click on OK button: Copy the systemjs. Angular. 2 Quick Start Git. Hub and paste it in newly added systemjs. Angular. 2MVC project: Next let’s add the Type. Script JSON Configuration File by right clicking on Angular. MVC project and Add - > New Item. Select Type. Script JSON Configuration File and click on OK button: Copy the tsconfig. Angular. 2 Quick Start Git. Hub and replace it with newly added tsconfig. Angular. 2MVC project: In case you are getting compilation error while trying to build, don’t worry. As soon we will start adding any typescript file, these errors will go away. Now that our Angular. ASP. NET MVC is almost completed, it’s time to develop the User Management application but first we need database with one table where we will save the user information. User Database & Entity Framework Model. Right click on App_Data folder and select Add - > New item. In Data section, you can find the SQL Server Database option. Select it and specify the name as User. DB. Once database is created, double click on User. DB. mdf database file to open the Tables: Right click on User. DB. mdf and select New Query. Paste the following SQL query to create the Tbl. User table, click on Execute button to create the table: CREATETABLE [dbo].[Tbl. User] (. [Id] INT IDENTITY (1, 1) NOTNULL. First. Name] NVARCHAR (2. NULL. [Last. Name] NVARCHAR (2. NULL. [Gender] NVARCHAR (2. NULL. PRIMARYKEYCLUSTERED ([Id] ASC). Right click on Tables folder and select option Refresh: Next lets develop the ASP. NET MVC side that includes setting up Layout and Index pages to load Angular. MVC controller to load index view and Web API 2. RESTful CRUD (Create, Read, Update and Delete) User APIs. Let’s first go to App_Start folder and configure the route to accept any URL since we can define our custom routing in Angular. Double click on Route. Config. cs file to edit it and change the URL in default route as following: using System. System. Collections. Generic. using System. Linq. using System. Web. using System. Web. Mvc. using System. Web. Routing. namespace Angular. MVC. publicclass Route. Config. publicstaticvoid Register. Routes(Route. Collection routes). Ignore. Route("{resource}. Info}"). routes. Map. Route(. name: "Default". Home", action = "Index", id = Url. Parameter. Optional }. Next let’s open our _Layout. Java. Scripts files to run the Angular. Views - > Shared - > _Layout. Remove the pre- added top menu and pages link. Add following JS files and system. System. import('app'). Just a brief intro what are these JS files. Zone. js: A Zone is an execution context that persists across async tasks. For more info click here. System. Configurable module loader enabling dynamic ES module workflows in browsers and Node. JS. For more info click here. Your final _Layout. Next let’s create the ADO. NET Entity Data Modal for User. DB database. Right Click on Angular. MVC project and select Add - > New Folder, specify the name DBContext or anything you want to: Right click on newly created folder DBContext and select Add - > New Item: From left Panel under Visual C#, select Data. On the right side select ADO. NET Entity Data Model. Enter the name User. DBEntities or any of your choice. Click on Add button. From next screen, select EF Designer for Data, click on Next button: Click on New Connection button on the next screen: On next screen, if Data Source is not selected as Microsoft SQL Server Database file (Sql. Client), click on Change button and select it: In Database file name, click on Browse button: Browse to User. DB databas created in earlier steps and saved in App_Data folder, click on OK button on both Select SQL Server Database File and Connection Properties windows: Check the Save Connection Settings in Web. Config as checkbox and click on Next button: In next screen, you can select the Entity Framework version, I am using 6. On next screen click on Tables checkbox, you would see the only one table Tbl. User, click on Finish button to end the wizard: It will take few seconds and finally you would see our database entity model having one table: Still at this point, if you would try to compile your project, you may get lot of typescript errors, in order to solve it, create the folder with the name app, right click on it and select Add - > Type. Script File: Enter the name main. OK (we will use this file in upcoming steps). Now rebuild the project, it should be successfully build. Develop User Management RESTful APIs. Next step is to create the ASP. NET MVC Web APIs for read, add, update and delete the user. First we will create the Parent API controller that will have common methods that all API controllers would share, for now we will have only one method to serialize the class object into JSON string for Angular. User. DB database DBContext object to perform database operation in child controller. Right click on Controllers folder and select Add - > Controller…: Select the Web API 2 Controller – Empty and click on Add button: Enter the name Base. APIController and click on Add button: Add following code in Base. APIController: protectedreadonly User. DBEntities User. DB = new User. DBEntities(). protected Http. Response. Message To. Json(dynamic obj). Request. Create. Response(Http. Status. Code. OK). Content = new String. Content(Json. Convert. Serialize. Object(obj), Encoding. UTF8, "application/json"). Above given code is quite self- explanatory, we are creating User. DBEntities class object named as User.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
November 2017
Categories |