.net core试水
概述
大概记录下我如何第一次使用.net core搭建一个api,由于最近.net core比较火,我也尝试着使用.net core做了一个小功能
本文主要包括
1.环境配置
2.程序编写
3.程序部署
主要参考:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio
1、环境配置
想要使用.net core3.1 第一个问题是更新VS,更新过程中遇到报错
VS_InstallerShell.exe has an invalid certificate. Please ensure the appropriate Microsoft certificates are installed
网上很多方法试过没有效果,最后在哪里(自己也忘记了)找到了解决方案,安装两个windows补丁,附上补丁编号和下载地址
https://www.catalog.update.microsoft.com/Home.aspx
KB4474419
kb4490628
2.程序编写
安装了最新vs以后,点击新建项目,创建3.1 .net core API项目,创建以后可以直接运行,会有一个天气预报的示例
使用Nuget安装Microsoft.EntityFrameworkCore.SqlServr,ef我虽然没有在实际项目中使用过,不过陆陆续续知道点,今天顺便试试
2.1 创建数据库上下文类
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 }
2.2 在startup.cs类中注入数据库上下文类,添加跨域配置
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 void ConfigureServices(IServiceCollection services) 27 { 28 //允许一个或多个具体来源: 29 services.AddCors(options => 30 { 31 // 配置跨域 32 options.AddPolicy("cors", policy => 33 { 34 // 设定允许跨域的来源,有多个的话可以用 `,` 隔开 35 policy 36 .AllowAnyOrigin() 37 .AllowAnyHeader() 38 .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 创建控制器,一共三个方法,获取列表,更新一条记录,获取一条记录
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 }
一个增删改完成
3.部署到服务器
部署比较简单,直接拷贝bin下面的内容,然后双击 项目名.exe 服务就启动起来了