立即注册 登录
汉山 返回首页

翰山的个人空间 http://s541722682.onlinehome.us/?2 [收藏] [复制] [分享] [RSS]

日志

Consume Web API By MVC Client In .NET Core (1), Server And Framework

已有 7113 次阅读2020-12-15 09:01 |个人分类:Tech|系统分类:原创博文 | 宽屏 请点击显示宽屏,再点击恢复窄屏 | 动漫全图 如只见部分动漫,请点击显示全图,再点击恢复窄图


This article will give a way with one line code to consume Web API by a ASP.NET MVC Client in .NET Core.
 

Introduction

 
Microservice is a modern software development architecture: loose-coupled architecture with application scope.  It basically includes two parts: Client and API.
 
Theoretically, API is a server, could be built by any languages or any platforms or any devices.
 
The client is the consumer of the API Server that, in turn, could be applications of a smartphone, tablet, Windows, Mac, or any kind of browsers, and could be built by any platfoms and languages.
 
ASP.NET Web API is, specifically, a Microsoft product to produce the RESTful output through HTTP for Clients. The consumer of ASP.NET Web API could be, say,
  • Javascript client,
  • Angular client,
  • Node.js client,
  • jQuery client,
  • C# code such as Console, MVC, WebForm, Windows, and so on.
This article, we consider the c# client, and specifically an ASP.NET MVC client in .NET Core.
 
If we google online, we might find out a lot articles that describe the C# client to consume Web API (see some of them from the references at the end of this article). However, most of them seem quite complex, and even you could follow the steps to build up a project, it is hard to catch the points to re-do one for yourself.
 
The contribution of this article is that I try to make one-line code to build the MVC Client, while before the one-line code, we will use all of the knowledge and techniques we are fimiliar with to build the server and client framework.
 
This article will be divided in two parts, Part I (this article) will create a ASP.NET Core Web API (server), and also a ASP.NET Core MVC module (Client base). The later one will be used as a framework of the one-line code MVC Client.Part II will implemente the one-line code Web API Client to be a Web API consumer.
 

A, Build ASP.NET MVC in .NET Core with Entity Framework Database First

 
This part will create a ASP.NET Core MVC application with Entity Framework Database first approach.
  • Step 1, Create an ASP.NET Core MVC application
  • Step 2, Reverse engineering Entity model from database (database first aproach for entity)
  • Step 3, Scaffold Controller with View using Entity Framework
  • Step 4, Run and Test app
At the end, you have an MVC app that can consume database directly through entity framework.
 

Step 1, Create an ASP.NET Core MVC application

 
We use the current version of Visual Studio 2019 16.8 and .NET 5.0 SDK to build the app.
  1. Start Visual Studio and select Create a new project.
  2. In the Create a new project dialog, select ASP.NET Core Web Application > Next.
  3. In the Configure your new project dialog, enter MVCCallWebAPI for Project name.
  4. Select Create.
  5. In the Create a new ASP.NET Core web application dialog, select,

    1. .NET Core and ASP.NET Core 5.0 in the dropdowns.
    2. ASP.NET Core Web App (Model-View-Controller).
    3. Create

 
 
Build and run the app, you will see the following image shows the app,
 

 

Step 2, Reverse engineering Entity model from database (database first aproach for entity)

 
We use a local Microsft SQL server, and the sample database pubs and its table stores as our database sample. We try to reverse engineering to get the table Stores into the project and make an entity model Store.
 
Click "Tools->NuGet Package Manager->Package Manager Console" as shown below i.e.
 

 
This is the reverse engineering command (when you run the command in PMC, you need to make it in one line),
  1. Scaffold-DbContext "Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer   
  2. -OutputDir Models/DB   
  3. -Table dbo.stores  
Run the command in the PMC,
 

 
We got error message above that Microsoft.EntityFrameworkCore.Design is required, but not installed. Click "Tools->NuGet Package Manager->Manage NuGet Packages for Solution" as shown below,
 

 
Choose and install: Microsoft.EntityFrameworkCore.Design,
 

 
Run the PMC command again, 
 

 
We got: Unable to find provider assembly 'Microsoft.EntityFrameworkCore.SqlServer', install it in the same way above from Manage NuGet Packages for Solution, and then reRun PMC command, we got successful and two classes are reverse engineered under Models/DB as shown below: pubsContext.cs and Store.cs
 

 

Step 3, Add Controller with View using Entity Framework

 
For the purpose to add controller, using entity framework, we need to modify the reverse engineered classes pubsContext and Store.cs. 
 
1, Modify the data connection
 
For the class pubsContext, we need to commend out the data connection part, 
  1. //        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  2. //        {  
  3. //            if (!optionsBuilder.IsConfigured)  
  4. //            {  
  5. //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.  
  6. //                optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");  
  7. //            }  
  8. //        }  
and move the data connection string into file appsettings.json,
  1. {        
  2.   "Logging": {        
  3.     "LogLevel": {        
  4.       "Default""Information",        
  5.       "Microsoft""Warning",        
  6.       "Microsoft.Hosting.Lifetime""Information"        
  7.     }        
  8.   },        
  9.         
  10.   "ConnectionStrings": {        
  11.     "DevConnection""Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"        
  12.   },        
  13.       
  14.   "AllowedHosts""*"        
  15. }    
Register the database connection context into Class starup.cs inside ConfigureServices,
 
  1. public void ConfigureServices(IServiceCollection services)        
  2. {        
  3.     // Register SQL database configuration context as services.         
  4.     services.AddDbContext<pubsContext>(options =>        
  5.     {        
  6.         options.UseSqlServer(Configuration.GetConnectionString("DevConnection"));        
  7.     });        
  8.         
  9.     services.AddControllersWithViews();        
  10. }    
Otherwise,  we could make a controller with view using this entity framework, and this would not work.
 
2, Modify the model
 
In class pubsContext, we can also commend out the data constrain part, 
  1. //protected override void OnModelCreating(ModelBuilder modelBuilder)    
  2. //{    
  3. //    modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");    
  4.     
  5. //    modelBuilder.Entity<Store>(entity =>    
  6. //    {    
  7. //        entity.HasKey(e => e.StorId)    
  8. //            .HasName("UPK_storeid");    
  9.     
  10. //        entity.ToTable("stores");    
  11.     
  12. //        entity.Property(e => e.StorId)    
  13. //            .HasMaxLength(4)    
  14. //            .IsUnicode(false)    
  15. //            .HasColumnName("stor_id")    
  16. //            .IsFixedLength(true);    
  17.     
  18. //        entity.Property(e => e.City)    
  19. //            .HasMaxLength(20)    
  20. //            .IsUnicode(false)    
  21. //            .HasColumnName("city");    
  22.     
  23. //        entity.Property(e => e.State)    
  24. //            .HasMaxLength(2)    
  25. //            .IsUnicode(false)    
  26. //            .HasColumnName("state")    
  27. //            .IsFixedLength(true);    
  28.     
  29. //        entity.Property(e => e.StorAddress)    
  30. //            .HasMaxLength(40)    
  31. //            .IsUnicode(false)    
  32. //            .HasColumnName("stor_address");    
  33.     
  34. //        entity.Property(e => e.StorName)    
  35. //            .HasMaxLength(40)    
  36. //            .IsUnicode(false)    
  37. //            .HasColumnName("stor_name");    
  38.     
  39. //        entity.Property(e => e.Zip)    
  40. //            .HasMaxLength(5)    
  41. //            .IsUnicode(false)    
  42. //            .HasColumnName("zip")    
  43. //            .IsFixedLength(true);    
  44. //    });    
  45.     
  46. //    OnModelCreatingPartial(modelBuilder);    
  47. //}    
  48.     
  49. //partial void OnModelCreatingPartial(ModelBuilder modelBuilder);    
but, we need to modify the data model to make the table member names are exactly the same as they are in database, such as Stor-Id into StorId, and add a  [Key] for primary key in database.
 
The class Store.cs, before,
  1. using System.ComponentModel.DataAnnotations;    
  2.   
  3. #nullable disable    
  4.     
  5. namespace MVCCallWebAPI.Models.DB    
  6. {    
  7.     public partial class Store    
  8.     {    
  9.         public string StorId { getset; }    
  10.         public string StorName { getset; }    
  11.         public string StorAddress { getset; }    
  12.         public string City { getset; }    
  13.         public string State { getset; }    
  14.         public string Zip { getset; }    
  15.     }    
  16. }     
After
  1. using System.ComponentModel.DataAnnotations;    
  2.   
  3. #nullable disable    
  4.     
  5. namespace MVCCallWebAPI.Models.DB    
  6. {    
  7.     public partial class Store    
  8.     {    
  9.         [Key]    
  10.         public string Stor_Id { getset; }    
  11.         public string Stor_Name { getset; }    
  12.         public string Stor_Address { getset; }    
  13.         public string City { getset; }    
  14.         public string State { getset; }    
  15.         public string Zip { getset; }    
  16.     }    
  17. }    
The final class pubsContext will be,
  1. using Microsoft.EntityFrameworkCore;  
  2.  
  3. #nullable disable  
  4.   
  5. namespace MVCCallWebAPI.Models.DB  
  6. {  
  7.     public partial class pubsContext : DbContext  
  8.     {  
  9.         public pubsContext()  
  10.         {  
  11.         }  
  12.   
  13.         public pubsContext(DbContextOptions<pubsContext> options)  
  14.             : base(options)  
  15.         {  
  16.         }  
  17.   
  18.         public virtual DbSet<Store> Stores { getset; }  
  19.   
  20. //        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  21. //        {  
  22. //            if (!optionsBuilder.IsConfigured)  
  23. //            {  
  24. //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.  
  25. //                optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");  
  26. //            }  
  27. //        }  
  28.   
  29.         //protected override void OnModelCreating(ModelBuilder modelBuilder)  
  30.         //{  
  31.         //    modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");  
  32.   
  33.         //    modelBuilder.Entity<Store>(entity =>  
  34.         //    {  
  35.         //        entity.HasKey(e => e.StorId)  
  36.         //            .HasName("UPK_storeid");  
  37.   
  38.         //        entity.ToTable("stores");  
  39.   
  40.         //        entity.Property(e => e.StorId)  
  41.         //            .HasMaxLength(4)  
  42.         //            .IsUnicode(false)  
  43.         //            .HasColumnName("stor_id")  
  44.         //            .IsFixedLength(true);  
  45.   
  46.         //        entity.Property(e => e.City)  
  47.         //            .HasMaxLength(20)  
  48.         //            .IsUnicode(false)  
  49.         //            .HasColumnName("city");  
  50.   
  51.         //        entity.Property(e => e.State)  
  52.         //            .HasMaxLength(2)  
  53.         //            .IsUnicode(false)  
  54.         //            .HasColumnName("state")  
  55.         //            .IsFixedLength(true);  
  56.   
  57.         //        entity.Property(e => e.StorAddress)  
  58.         //            .HasMaxLength(40)  
  59.         //            .IsUnicode(false)  
  60.         //            .HasColumnName("stor_address");  
  61.   
  62.         //        entity.Property(e => e.StorName)  
  63.         //            .HasMaxLength(40)  
  64.         //            .IsUnicode(false)  
  65.         //            .HasColumnName("stor_name");  
  66.   
  67.         //        entity.Property(e => e.Zip)  
  68.         //            .HasMaxLength(5)  
  69.         //            .IsUnicode(false)  
  70.         //            .HasColumnName("zip")  
  71.         //            .IsFixedLength(true);  
  72.         //    });  
  73.   
  74.         //    OnModelCreatingPartial(modelBuilder);  
  75.         //}  
  76.   
  77.         //partial void OnModelCreatingPartial(ModelBuilder modelBuilder);  
  78.     }  

3, Add the controller
 
In Solution Explorer, right-click the Controllers folder > Add > New Scaffolded Item. Then, select MVC Controller with views, using Entity Framework > Add.
 

 
Complete the Add MVC Controller with Views, using Entity Framework dialog,
  • Model class - Store(MVCCallWebAPI.Models.DB)
  • Data context class - pubsContext (MVCCallWebAPI.Models.DB)
  • Views - Keep the default of each option checked
  • Controller name - Change the default StoresController to StoresMVCController
  • Select Add


 
Visual Studio creates,
  • A StroesMVC controller (Controllers/StoresMVCController.cs)
  • Razor view files for Create, Delete, Details, Edit, and Index pages (Views/StoresMVC/*.cshtml)

 
The automatic creation of these files is known as scaffolding.
 
Step 4, Run and Test the app
 
Before we run the app, modify the header of the file: Views/Shared/_layout.cshtml Views, shown below, change the controller as StoreMVC and the app name as MVC app:
  1. <header>    
  2.     <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">    
  3.         <div class="container">    
  4.             <a class="navbar-brand" asp-area="" asp-controller="StroeMVC" asp-action="Index">MVC app</a>    
  5.             <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"    
  6.                     aria-expanded="false" aria-label="Toggle navigation">    
  7.                 <span class="navbar-toggler-icon"></span>    
  8.             </button>    
  9.             <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">    
  10.                 <ul class="navbar-nav flex-grow-1">    
  11.                     <li class="nav-item">    
  12.                         <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>    
  13.                     </li>    
  14.                     <li class="nav-item">    
  15.                         <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>    
  16.                     </li>    
  17.                 </ul>    
  18.             </div>    
  19.         </div>    
  20.     </nav>    
  21. </header>     
Now, we run the app,
,
 

 
Click MVC app, we got the screen,
 

 
This is a MVC app that consume database directly through entity framework.
 

B, Add Web API with Entity Framework Code First

 
This part will add a ASP.NET Core Web API into the app with Entity Framework code first approach.
  • Step 1, Set up a new Database context
  • Step 2, Work with a database using Entity Framework code first appoach.
  • Step 3, Scaffold API Controller with Action using Entity Framework
  • Step 4, Add Swagger client for Web API
  • Step 5, Run and Test app
At the end, you have an Web API built in a MVC app. The Web API is consumed by Swagger interface and can be consumed by any other interfaces, such as Postman.
 
Step 1, Set up a new Database Context
 
We make a new database context with the same model, Model/Store.cs, and different database, DB_Demo_API:
 
1, Create a new Database Context class, named DB_Demo_APIContext.cs,
  1. using Microsoft.EntityFrameworkCore;    
  2.   
  3. #nullable disable    
  4.     
  5. namespace MVCCallWebAPI.Models.DB    
  6. {    
  7.     public partial class DB_Demo_APIContext : DbContext    
  8.     {    
  9.         public DB_Demo_APIContext()    
  10.         {    
  11.         }    
  12.     
  13.         public DB_Demo_APIContext(DbContextOptions<DB_Demo_APIContext> options)    
  14.             : base(options)    
  15.         {    
  16.         }    
  17.     
  18.         public virtual DbSet<Store> Stores { getset; }    
  19.     
  20.     }    
  21. }     
2. Add the new Connection in the appsettings.json file,
  1. {        
  2.   "Logging": {        
  3.     "LogLevel": {        
  4.       "Default""Information",        
  5.       "Microsoft""Warning",        
  6.       "Microsoft.Hosting.Lifetime""Information"        
  7.     }        
  8.   },        
  9.         
  10.   "ConnectionStrings": {        
  11.     "DevConnection""Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"        
  12.   },        
  13.         
  14.   "ConnectionStrings": {        
  15.     "DB_Demo_APIConnection""Data Source=localhost;Initial Catalog=DB_Demo_API;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"        
  16.   },        
  17.         
  18.   "AllowedHosts""*"        
  19. }   
3. Register the database connection context into Class starup.cs inside ConfigureServices,
  1. public void ConfigureServices(IServiceCollection services)      
  2. {       
  3.     // Register SQL database configuration context as services.       
  4.     services.AddDbContext<pubsContext>(options =>      
  5.     {  options.UseSqlServer(Configuration.GetConnectionString("DevConnection"));      
  6.     });      
  7.     services.AddDbContext<DB_Demo_APIContext>(options =>      
  8.     {      
  9.         options.UseSqlServer(Configuration.GetConnectionString("DB_Demo_APIConnection"));      
  10.     });      
  11.       
  12.     services.AddControllersWithViews();      
  13. }      

Step 2, Work with a database using Entity Framework code first appoach.

 
Click "Tools->NuGet Package Manager->Package Manager Console"(See A-Step 2), and run the PMC command (make them in one line),
  1. Add-Migration   
  2. -Name initialMigration   
  3. -Context DB_Demo_APIContext     
We got two migration files under Migration folder,
 

 
Run PMC command,
      Update-Database   

We got the database table Stores created in database DB_Demo_API

 

Step 3, Scaffold API Controller with Action using Entity Framework

  • Right-click the Controllers folder.
  • Select Add > New Scaffolded Item.
  • Select API Controller with actions, using Entity Framework, and then select Add.

  • In the Add API Controller with actions, using Entity Framework dialog,
    • Model class -Store(MVCCallWebAPI.Models.DB)
    • Data context class - DB_Demo_APIContext (MVCCallWebAPI.Models.DB)
    • Controller name - Change the default StoresController to StoresWebAPIController
    • Select Add

     
The generated code,
  • Marks the class with the [ApiController]attribute. This attribute indicates that the controller responds to webAPI requests.
  • Uses DI to inject the database context (DB_Demo_APIContext) into the controller. The database context is used in each of the CRUD methods in the controller.

Step 4, Add Swagger client for Web API

 
Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification.
 
If we created a new Web API project, the Swagger cient for Web API would be installeld by default. In our current case, the Web API is created in a MVC module, so we need to install Swagger manually.
 
1, Install Swagger Client
 
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger
 

 
There are three main components to Swashbuckle(Swagger), we only need to install two of them: SwaggerGen and SwaggerUI, the Swagger would be included.
 
2, Register Swagger Client in startup.json file
 
Add the Swagger generator to the services collection in the Startup.ConfigureServices method,
  1. // This method gets called by the runtime. Use this method to add services to the container.        
  2. public void ConfigureServices(IServiceCollection services)        
  3. {        
  4.     // Register the Swagger generator, defining 1 or more Swagger documents        
  5.     services.AddSwaggerGen(c =>        
  6.     {        
  7.         c.SwaggerDoc("v2"new OpenApiInfo { Title = "MVCCallWebAPI", Version = "v2" });        
  8.     });        
  9.     ......      
  10. }   
Enable the middleware for serving the generated JSON document and the Swagger UI, in the Startup.Configure method,
  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        
  2. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        
  3. {        
  4.     // Enable middleware to serve generated Swagger as a JSON endpoint.        
  5.     app.UseSwagger();        
  6.         
  7.     // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),        
  8.     // specifying the Swagger JSON endpoint.        
  9.     app.UseSwaggerUI(c =>        
  10.     {        
  11.         c.SwaggerEndpoint("/swagger/v2/swagger.json""MVCCallWebAPI");        
  12.     });        
  13.     ......      
  14. }      
Now, we are almost ready to run the app.
 

Step 5, Run and Test the app

Before we run the app, modify the header of the file: Views/Shared/_layout.cshtml Views again, shown below,
  1. <header>        
  2.     <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">        
  3.         <div class="container">        
  4.             <a class="navbar-brand" asp-area="" asp-controller="StoresMVC" asp-action="Index">MVC app</a>        
  5.             <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"        
  6.                     aria-expanded="false" aria-label="Toggle navigation">        
  7.                 <span class="navbar-toggler-icon"></span>        
  8.             </button>        
  9.             <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">        
  10.                 <ul class="navbar-nav flex-grow-1">        
  11.                     <li class="nav-item">        
  12.                         <a class="nav-link text-dark" asp-area="" asp-controller="Swagger" asp-action="Index">Web API</a>        
  13.                     </li>        
  14.                     <li class="nav-item">        
  15.                         <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>        
  16.                     </li>        
  17.                     <li class="nav-item">        
  18.                         <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>        
  19.                     </li>        
  20.                 </ul>        
  21.             </div>        
  22.         </div>        
  23.     </nav>        
  24. </header>       
Now, we run the app,

 
Click Web API, we got the Swagger Client screen,
 

 

Summary

 
In this article (part I), we create a ASP.NET Core 5.0 MVC app and associated with a Web API service in it.
  • MVC is a client/server app, with a web page as a client and SQL server as server, linked by Entity Framework;
  • Web API is a Server side service, with a RESTful output for consumer that is linked to database by entity framework.
For our test purpose, MVC and Web API are against two different database, MVC is against the database pubs, while Web API against database DB_Demo_API, which also gave us chance to practice the entity framework database first approach and code first approach, respectively, in this mini project.
 
In this article part II, we will demostrate the one line code approach for the MVC Client to consume Web API
 
References

鲜花

真棒

玩闹

同情

看看

困惑

震惊

bad

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 立即注册

Archiver|手机版|小黑屋|汉山网    

GMT-5, 2024-4-19 07:04 , Processed in 0.037803 second(s), 20 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

返回顶部