.net core to test the water

Outline

How about the next record my first time to build a .net core api, due to the relatively recent .net core fire, I also try to use the .net core did a small feature

This article includes

1. Environment Configuration

2. writing program

3. Deployment

The main reference: https:? //Docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api view = aspnetcore-3.1 & tabs = visual-studio

1, environment configuration

The first question you want to use .net core3.1 update VS, encountered during an update error

VS_InstallerShell.exe has an invalid certificate. Please ensure the appropriate Microsoft certificates are installed

Online tried many methods to no avail, and finally where (himself forgotten) to find a solution, install two windows patch, patch number and enclose Download

https://www.catalog.update.microsoft.com/Home.aspx

KB4474419
Kb4490628

2. writing program

After the latest vs installation, click New Project to create 3.1 .net core API project, create the future can be run directly, there will be an example of weather forecast

Use Nuget installation Microsoft.EntityFrameworkCore.SqlServr, ef although I have not used in the actual project before, but after another point to know, by the way try today

2.1 Create a database context classes

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.Data.SqlClient;
 6 using Microsoft.EntityFrameworkCore;
 7 
 8 namespace reportAPI
 9 {
10     public class ChartDesignContenxt: DbContext
11     {
12         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
13         {
14             var sqlConnectionStringBuilder = new SqlConnectionStringBuilder
15             {
16                 DataSource = "*.*.*.*",
17                 InitialCatalog = "*",
18                 UserID = "sa",
19                 Password = "123456"
20             };
21             optionsBuilder.UseSqlServer(sqlConnectionStringBuilder.ConnectionString);
22 
23             base.OnConfiguring(optionsBuilder);
24         }
25         public DbSet<chartDesign> chartDesigns { get; set; }
26     }
27 }

Injection in 2.2 startup.cs context class database class, add cross-domain configuration

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.AspNetCore.HttpsPolicy;
 8 using Microsoft.AspNetCore.Mvc;
 9 using Microsoft.Extensions.Configuration;
10 using Microsoft.Extensions.DependencyInjection;
11 using Microsoft.Extensions.Hosting;
12 using Microsoft.Extensions.Logging;
13 
14 namespace reportAPI
15 {
16     public class Startup
17     {
18         public Startup(IConfiguration configuration)
19         {
20             Configuration = configuration;
21         }
22 
23         public IConfiguration Configuration { get; }
24 
25         // This method gets called by the runtime. Use this method to add services to the container.
26         public voidConfigureServices (IServiceCollection Services)
 27          {
 28              // allow one or more specific sources: 
29              services.AddCors (Options =>
 30              {
 31 is                  // configuring inter 
32                  options.AddPolicy ( " CORS " , Policy =>
 33 is                  {
 34 is                      / / settings allow cross-domain sources, a plurality of words can be `` spaced 
35                      Policy
 36                              .AllowAnyOrigin ()
 37 [                              .AllowAnyHeader ()
 38 is                              .AllowAnyMethod ();
 39                 });
40             });
41 
42             services.AddScoped<IPMSDbContenxt>(_ => new IPMSDbContenxt());   
43             services.AddScoped<ChartDesignContenxt>(_ => new ChartDesignContenxt());   //注入数据库上下文类
44 
45             services.AddControllers();
46         }
47 
48         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
49         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
50         {
51             if (env.IsDevelopment())
52             {
53                 app.UseDeveloperExceptionPage();
54             }
55 
56             app.UseHttpsRedirection();
57 
58             app.UseRouting();
59     
60             app.UseCors("cors");  //使用跨域
61 
62             app.UseAuthorization();
63 
64             app.UseEndpoints(endpoints =>
65             {
66                 endpoints.MapControllers();
67             });
68         }
69     }
70 }

 

2.3 Creating a controller, a total of three methods for a list, update a record, get a record

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Http;
 6 using Microsoft.AspNetCore.Mvc;
 7 using Microsoft.EntityFrameworkCore;
 8 
 9 namespace reportAPI.Controllers
10 {
11     [Route("api/[controller]/[action]")]
12     [ApiController]
13     public class ChartDesignController : ControllerBase
14     {
15         private readonly ChartDesignContenxt _context;
16 
17         public ChartDesignController(ChartDesignContenxt context)
18         {
19             _context = context;
20         }
21 
22         [HttpPost]
23         public IActionResult Save(CommonFilter filter)
24         {
25             try
26             {
27                 //var temp = entity.data.ToString();
28                 chartDesign model = new chartDesign();
29                 model.designName = filter.field1;
30                 model.designContent = filter.data.ToString();
31                 if (filter.key == -1)
32                 {
33                     _context.Add<chartDesign>(model);
34                 }
35                 else
36                 {
37                     model.designId = filter.key;
38                     _context.Update<chartDesign>(model);
39                 }
40                 _context.SaveChanges();
41                 return Ok("保存成功");
42             }
43             catch(Exception ex)
44             {
45                 return Ok(ex.Message);
46             }
47            
48         }
49         [HttpPost]
50         public IActionResult Get(CommonFilter filter)
51         {
52             try
53             {
54                 chartDesign entity = _context.chartDesigns.Find(filter.key);
55                 if (entity == null)
56                 {
57                     return NotFound();
58                 }
59 
60                 return Ok(entity);
61             }
62             catch(Exception ex)
63             {
64                 return Ok(ex.Message);
65             }
66         }
67         [HttpPost]
68         public IActionResult GetList()
69         {
70             try
71             {
72                 string sql = "select * from chartDesign";
73                 List<chartDesign> list = _context.chartDesigns.ToList(); //.FromSqlRaw(sql).ToList();
74                 return Ok(list);
75             }
76             catch (Exception ex)
77             {
78                 return Ok(ex.Message);
79             }
80         }
81     }
82 }

A complete CRUD

3. deployed to the server

Deployment is simple, direct copy bin below, and then double-click the project name .exe service started up

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/lovejunjuan/p/12155795.html
Recommended