概述

大概记录下我如何第一次使用.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 创建数据库上下文类

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore; namespace reportAPI
{
public class ChartDesignContenxt: DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var sqlConnectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = "*.*.*.*",
InitialCatalog = "*",
UserID = "sa",
Password = ""
};
optionsBuilder.UseSqlServer(sqlConnectionStringBuilder.ConnectionString); base.OnConfiguring(optionsBuilder);
}
public DbSet<chartDesign> chartDesigns { get; set; }
}
}

2.2 在startup.cs类中注入数据库上下文类,添加跨域配置

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; namespace reportAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//允许一个或多个具体来源:
services.AddCors(options =>
{
// 配置跨域
options.AddPolicy("cors", policy =>
{
// 设定允许跨域的来源,有多个的话可以用 `,` 隔开
policy
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
}); services.AddScoped<IPMSDbContenxt>(_ => new IPMSDbContenxt());
services.AddScoped<ChartDesignContenxt>(_ => new ChartDesignContenxt()); //注入数据库上下文类 services.AddControllers();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("cors"); //使用跨域 app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

2.3 创建控制器,一共三个方法,获取列表,更新一条记录,获取一条记录

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; namespace reportAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ChartDesignController : ControllerBase
{
private readonly ChartDesignContenxt _context; public ChartDesignController(ChartDesignContenxt context)
{
_context = context;
} [HttpPost]
public IActionResult Save(CommonFilter filter)
{
try
{
//var temp = entity.data.ToString();
chartDesign model = new chartDesign();
model.designName = filter.field1;
model.designContent = filter.data.ToString();
if (filter.key == -)
{
_context.Add<chartDesign>(model);
}
else
{
model.designId = filter.key;
_context.Update<chartDesign>(model);
}
_context.SaveChanges();
return Ok("保存成功");
}
catch(Exception ex)
{
return Ok(ex.Message);
} }
[HttpPost]
public IActionResult Get(CommonFilter filter)
{
try
{
chartDesign entity = _context.chartDesigns.Find(filter.key);
if (entity == null)
{
return NotFound();
} return Ok(entity);
}
catch(Exception ex)
{
return Ok(ex.Message);
}
}
[HttpPost]
public IActionResult GetList()
{
try
{
string sql = "select * from chartDesign";
List<chartDesign> list = _context.chartDesigns.ToList(); //.FromSqlRaw(sql).ToList();
return Ok(list);
}
catch (Exception ex)
{
return Ok(ex.Message);
}
}
}
}

一个增删改完成

3.部署到服务器

部署比较简单,直接拷贝bin下面的内容,然后双击  项目名.exe 服务就启动起来了

最新文章

  1. 修改pip更新源
  2. Alpha阶段发布说明
  3. T-SQL 语句的优化
  4. valueForKeyPath常用用法
  5. 获取全国市以及地理坐标,各大坐标系北斗,百度,WGS-84坐标系的转换,有图,有代码
  6. android动态调试samli代码(转)
  7. (转载)直接用SQL语句把DBF导入SQLServer
  8. C语言学习_一个简单程序的解释与C学习方法概括
  9. Toast的使用具体解释
  10. 2014 android毕设代做 代做Android毕设 安卓毕设
  11. ThinkPhp_5框架开发【整理】
  12. 查看 Secret - 每天5分钟玩转 Docker 容器技术(156)
  13. MSM8909的触摸屏驱动导致的熄屏后重新亮屏速度慢的原因!【转】
  14. docker-compose部署ELK
  15. C语言之递归
  16. Perl的time、localtime和gmtime函数
  17. lanmp安装
  18. ArcGIS Server Rest 认证过程分析
  19. 使用mysqladmin extended-status查看MySQL的运行状态脚本
  20. Zookeeper简介说明

热门文章

  1. H3C ACL包过滤显示与调试
  2. ReadTimeoutError: HTTPSConnectionPool(host=&#39;files.pythonhosted.org&#39;, port=443): Read timed out.
  3. .net连接数据库
  4. P1047 汉诺塔
  5. vmware虚拟机卸载干净在注册表的也需要删除
  6. C# 从零开始写 SharpDx 应用 绘制基础图形
  7. computed计算属性(二)
  8. mysql(8.0.16)安装及使用注意事项
  9. OpenCV与MFC实战之图像处理 样本采集小工具制作 c++MFC课程设计
  10. 2019牛客多校第一场 I Points Division(动态规划+线段树)