找回密码
 立即注册

QQ登录

只需一步,快速开始

Lenka.Guo 讲师达人认证 悬赏达人认证
超级版主   /  发表于:2021-11-4 10:14  /   查看:1745  /  回复:0
示例源码:


操作步骤:

1. 使用Mysql工具创建我们需要的mysql database 表
  1. CREATE TABLE dbo.department(
  2.   DepartmentId int AUTO_INCREMENT,
  3.   DepartmentName nvarchar(500),
  4.   PRIMARY KEY (DepartmentId)
  5. )
复制代码
插入表:
  1. INSERT into dbo.Department (DepartmentName) VALUES ('IT')
  2. INSERT into dbo.Department (DepartmentName) VALUES ('Support')
复制代码


employee表:


  1. create table dbo.Employee(
  2. EmployeeId int AUTO_INCREMENT,
  3. EmployeeName nvarchar(500),
  4. Department nvarchar(500),
  5. DateOfJoining datetime,
  6. PhotoFileName nvarchar(500),
  7. PRIMARY KEY(EmployeeId)
  8. );

  9. insert into dbo.Employee(EmployeeName,Department,DateOfJoining,PhotoFileName)
  10. values                  ('Bob','IT','2021-06-21','anonymous.png');

  11. select * from dbo.Employee;
复制代码
2. 创建.Net Core Web API 项目


-> launchSettings.json :文件包含了如何启动项目的细节描述
-> Controllers 文件夹:包含了API controler 方法
-> We generally keep the configuration details such as database details in appSettings.json.
-> program.cs 是程序的主入口 Main() 它还创建了网络主机,基本上可以帮助应用程序监听http请求。
-> startup类 class 类配置了我们的应用程序所需的所有服务。类配置了我们应用程序所需的所有服务。服务基本上是可重复使用的组件,可以使用依赖性在我们的应用程序中使用。


3. 配置允许跨域:


  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.HttpsPolicy;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Hosting;
  8. using Microsoft.Extensions.Logging;
  9. using Microsoft.OpenApi.Models;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Threading.Tasks;

  14. namespace WebApplication11
  15. {
  16.     public class Startup
  17.     {
  18.         public Startup(IConfiguration configuration)
  19.         {
  20.             Configuration = configuration;
  21.         }

  22.         public IConfiguration Configuration { get; }

  23.         // This method gets called by the runtime. Use this method to add services to the container.
  24.         public void ConfigureServices(IServiceCollection services)
  25.         {
  26.             services.AddCors(c=> {
  27.                 c.AddPolicy("AllowOrigin",options=>options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
  28.             });
  29.             services.AddControllers();
  30.             services.AddSwaggerGen(c =>
  31.             {
  32.                 c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication11", Version = "v1" });
  33.             });
  34.         }

  35.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  36.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  37.         {
  38.             if (env.IsDevelopment())
  39.             {
  40.                 app.UseDeveloperExceptionPage();
  41.                 app.UseSwagger();
  42.                 app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication11 v1"));
  43.             }

  44.             app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
  45.             app.UseHttpsRedirection();

  46.             app.UseRouting();

  47.             app.UseAuthorization();

  48.             app.UseEndpoints(endpoints =>
  49.             {
  50.                 endpoints.MapControllers();
  51.             });
  52.         }
  53.     }
  54. }
复制代码




4. 安装 JSON 序列化nuget 包 帮助我们提供JSON 序列化和反序列化的函数



Startup.cs 完整代码:
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.HttpsPolicy;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.FileProviders;
  8. using Microsoft.Extensions.Hosting;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.OpenApi.Models;
  11. using Newtonsoft.Json.Serialization;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading.Tasks;

  17. namespace WebApplication11
  18. {
  19.     public class Startup
  20.     {
  21.         public Startup(IConfiguration configuration)
  22.         {
  23.             Configuration = configuration;
  24.         }

  25.         public IConfiguration Configuration { get; }

  26.         // This method gets called by the runtime. Use this method to add services to the container.
  27.         public void ConfigureServices(IServiceCollection services)
  28.         {
  29.             services.AddCors(c=> {
  30.                 c.AddPolicy("AllowOrigin",options=>options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
  31.             });
  32.             services.AddControllersWithViews().AddNewtonsoftJson(options =>
  33.             options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
  34.                 .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver
  35.                 = new DefaultContractResolver());

  36.             services.AddControllers();
  37.             services.AddControllers();
  38.             services.AddSwaggerGen(c =>
  39.             {
  40.                 c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication11", Version = "v1" });
  41.             });
  42.         }

  43.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  44.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  45.         {
  46.             if (env.IsDevelopment())
  47.             {
  48.                 app.UseDeveloperExceptionPage();
  49.                 app.UseSwagger();
  50.                 app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication11 v1"));
  51.             }

  52.             app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
  53.             app.UseHttpsRedirection();

  54.             app.UseRouting();

  55.             app.UseAuthorization();

  56.             app.UseEndpoints(endpoints =>
  57.             {
  58.                 endpoints.MapControllers();
  59.             });

  60.             app.UseStaticFiles(new StaticFileOptions
  61.             {
  62.                 FileProvider = new PhysicalFileProvider(
  63.                  Path.Combine(Directory.GetCurrentDirectory(), "Photos")),
  64.                 RequestPath = "/Photos"
  65.             });
  66.         }
  67.     }
  68. }
复制代码


以下代码是指定图像上传的地址:
  1. {
  2.                 FileProvider = new PhysicalFileProvider(
  3.                    Path.Combine(Directory.GetCurrentDirectory(), "Photos")),
  4.                 RequestPath = "/Photos"
  5.             });
复制代码



5. 为了连接Mysql 数据库,先安装MysqlData nuget包



6.  添加数据模型 Model:

Department.cs:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;

  5. namespace WebApplication1.Models
  6. {
  7.     public class Department
  8.     {
  9.         public int DepartmentId { get; set; }

  10.         public string DepartmentName { get; set; }
  11.     }
  12. }
复制代码
Employee.cs:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;

  5. namespace WebApplication1.Models
  6. {
  7.     public class Employee
  8.     {
  9.         public int EmployeeId { get; set; }
  10.         public string EmployeeName {get; set; }
  11.         public string Department { get; set; }

  12.         public string DateOfJoining { get; set; }

  13.         public string  PhotoFileName { get; set; }
  14.     }
  15. }
复制代码


7. 在appSettings.json 文件中添加数据库连接字符串:


8. 添加对应Model的controller:
DepartmentController.cs:
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Configuration;
  4. using MySql.Data.MySqlClient;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. using WebApplication1.Models;

  11. namespace WebApplication1.Controllers
  12. {
  13.     [Route("api/[controller]")]
  14.     [ApiController]
  15.     public class DepartmentController : ControllerBase
  16.     {
  17.         private readonly IConfiguration _configuration;
  18.         public DepartmentController(IConfiguration configuration)
  19.         {
  20.             _configuration = configuration;
  21.         }

  22.         [HttpGet]
  23.         public JsonResult Get()
  24.         {
  25.             string query = @"
  26.                         select DepartmentId,DepartmentName from
  27.                         dbo.Department
  28.             ";

  29.             DataTable table = new DataTable();
  30.             string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
  31.             MySqlDataReader myReader;
  32.             using(MySqlConnection mycon=new MySqlConnection(sqlDataSource))
  33.             {
  34.                 mycon.Open();
  35.                 using(MySqlCommand myCommand=new MySqlCommand(query, mycon))
  36.                 {
  37.                     myReader = myCommand.ExecuteReader();
  38.                     table.Load(myReader);

  39.                     myReader.Close();
  40.                     mycon.Close();
  41.                 }
  42.             }

  43.             return new JsonResult(table);
  44.         }


  45.         [HttpPost]
  46.         public JsonResult Post(Department dep)
  47.         {
  48.             string query = @"
  49.                         insert into dbo.Department (DepartmentName) values
  50.                                                     (@DepartmentName);
  51.                         
  52.             ";

  53.             DataTable table = new DataTable();
  54.             string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
  55.             MySqlDataReader myReader;
  56.             using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
  57.             {
  58.                 mycon.Open();
  59.                 using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  60.                 {
  61.                     myCommand.Parameters.AddWithValue("@DepartmentName", dep.DepartmentName);
  62.                     
  63.                     myReader = myCommand.ExecuteReader();
  64.                     table.Load(myReader);

  65.                     myReader.Close();
  66.                     mycon.Close();
  67.                 }
  68.             }

  69.             return new JsonResult("Added Successfully");
  70.         }


  71.         [HttpPut]
  72.         public JsonResult Put(Department dep)
  73.         {
  74.             string query = @"
  75.                         update dbo.Department set
  76.                         DepartmentName =@DepartmentName
  77.                         where DepartmentId=@DepartmentId;
  78.                         
  79.             ";

  80.             DataTable table = new DataTable();
  81.             string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
  82.             MySqlDataReader myReader;
  83.             using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
  84.             {
  85.                 mycon.Open();
  86.                 using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  87.                 {
  88.                     myCommand.Parameters.AddWithValue("@DepartmentId", dep.DepartmentId);
  89.                     myCommand.Parameters.AddWithValue("@DepartmentName", dep.DepartmentName);

  90.                     myReader = myCommand.ExecuteReader();
  91.                     table.Load(myReader);

  92.                     myReader.Close();
  93.                     mycon.Close();
  94.                 }
  95.             }

  96.             return new JsonResult("Updated Successfully");
  97.         }



  98.         [HttpDelete("{id}")]
  99.         public JsonResult Delete(int id)
  100.         {
  101.             string query = @"
  102.                         delete from dbo.Department
  103.                         where DepartmentId=@DepartmentId;
  104.                         
  105.             ";

  106.             DataTable table = new DataTable();
  107.             string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
  108.             MySqlDataReader myReader;
  109.             using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
  110.             {
  111.                 mycon.Open();
  112.                 using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  113.                 {
  114.                     myCommand.Parameters.AddWithValue("@DepartmentId", id);

  115.                     myReader = myCommand.ExecuteReader();
  116.                     table.Load(myReader);

  117.                     myReader.Close();
  118.                     mycon.Close();
  119.                 }
  120.             }

  121.             return new JsonResult("Deleted Successfully");
  122.         }

  123.     }
  124. }
复制代码
EmployeeController.cs:
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Configuration;
  5. using MySql.Data.MySqlClient;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading.Tasks;
  12. using WebApplication1.Models;

  13. namespace WebApplication1.Controllers
  14. {
  15.     [Route("api/[controller]")]
  16.     [ApiController]
  17.     public class EmployeeController : ControllerBase
  18.     {
  19.         private readonly IConfiguration _configuration;
  20.         private readonly IWebHostEnvironment _env;
  21.         public EmployeeController(IConfiguration configuration,IWebHostEnvironment env)
  22.         {
  23.             _configuration = configuration;
  24.             _env = env;
  25.         }

  26.         [HttpGet]
  27.         public JsonResult Get()
  28.         {
  29.             string query = @"
  30.                         select EmployeeId,EmployeeName,Department,
  31.                         DATE_FORMAT(DateOfJoining,'%Y-%m-%d') as DateOfJoining,
  32.                         PhotoFileName
  33.                         from
  34.                         dbo.Employee
  35.             ";

  36.             DataTable table = new DataTable();
  37.             string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
  38.             MySqlDataReader myReader;
  39.             using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
  40.             {
  41.                 mycon.Open();
  42.                 using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  43.                 {
  44.                     myReader = myCommand.ExecuteReader();
  45.                     table.Load(myReader);

  46.                     myReader.Close();
  47.                     mycon.Close();
  48.                 }
  49.             }

  50.             return new JsonResult(table);
  51.         }


  52.         [HttpPost]
  53.         public JsonResult Post(Employee emp)
  54.         {
  55.             string query = @"
  56.                         insert into dbo.Employee
  57.                         (EmployeeName,Department,DateOfJoining,PhotoFileName)
  58.                         values
  59.                          (@EmployeeName,@Department,@DateOfJoining,@PhotoFileName) ;
  60.                         
  61.             ";

  62.             DataTable table = new DataTable();
  63.             string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
  64.             MySqlDataReader myReader;
  65.             using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
  66.             {
  67.                 mycon.Open();
  68.                 using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  69.                 {
  70.                     myCommand.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName);
  71.                     myCommand.Parameters.AddWithValue("@Department", emp.Department);
  72.                     myCommand.Parameters.AddWithValue("@DateOfJoining", emp.DateOfJoining);
  73.                     myCommand.Parameters.AddWithValue("@PhotoFileName", emp.PhotoFileName);

  74.                     myReader = myCommand.ExecuteReader();
  75.                     table.Load(myReader);

  76.                     myReader.Close();
  77.                     mycon.Close();
  78.                 }
  79.             }

  80.             return new JsonResult("Added Successfully");
  81.         }


  82.         [HttpPut]
  83.         public JsonResult Put(Employee emp)
  84.         {
  85.             string query = @"
  86.                         update dbo.Employee set
  87.                         EmployeeName =@EmployeeName,
  88.                         Department =@Department,
  89.                         DateOfJoining =@DateOfJoining,
  90.                         PhotoFileName =@PhotoFileName
  91.                         where EmployeeId=@EmployeeId;
  92.                         
  93.             ";

  94.             DataTable table = new DataTable();
  95.             string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
  96.             MySqlDataReader myReader;
  97.             using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
  98.             {
  99.                 mycon.Open();
  100.                 using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  101.                 {
  102.                     myCommand.Parameters.AddWithValue("@EmployeeId", emp.EmployeeId);
  103.                     myCommand.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName);
  104.                     myCommand.Parameters.AddWithValue("@Department", emp.Department);
  105.                     myCommand.Parameters.AddWithValue("@DateOfJoining", emp.DateOfJoining);
  106.                     myCommand.Parameters.AddWithValue("@PhotoFileName", emp.PhotoFileName);

  107.                     myReader = myCommand.ExecuteReader();
  108.                     table.Load(myReader);

  109.                     myReader.Close();
  110.                     mycon.Close();
  111.                 }
  112.             }

  113.             return new JsonResult("Updated Successfully");
  114.         }



  115.         [HttpDelete("{id}")]
  116.         public JsonResult Delete(int id)
  117.         {
  118.             string query = @"
  119.                         delete from dbo.Employee
  120.                         where EmployeeId=@EmployeeId;
  121.                         
  122.             ";

  123.             DataTable table = new DataTable();
  124.             string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
  125.             MySqlDataReader myReader;
  126.             using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
  127.             {
  128.                 mycon.Open();
  129.                 using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  130.                 {
  131.                     myCommand.Parameters.AddWithValue("@EmployeeId", id);

  132.                     myReader = myCommand.ExecuteReader();
  133.                     table.Load(myReader);

  134.                     myReader.Close();
  135.                     mycon.Close();
  136.                 }
  137.             }

  138.             return new JsonResult("Deleted Successfully");
  139.         }


  140.         [Route("SaveFile")]
  141.         [HttpPost]
  142.         public JsonResult SaveFile()
  143.         {
  144.             try
  145.             {

  146.                 var httpReuest = Request.Form;
  147.                 var postedFile = httpReuest.Files[0];
  148.                 string filename = postedFile.FileName;
  149.                 var physicalPath = _env.ContentRootPath + "/Photos/" + filename;

  150.                 using(var stream=new FileStream(physicalPath, FileMode.Create))
  151.                 {
  152.                     postedFile.CopyTo(stream);
  153.                 }

  154.                 return new JsonResult(filename);
  155.             }
  156.             catch (Exception)
  157.             {

  158.                 return new JsonResult("anonymous.png");
  159.             }
  160.         }
  161.     }
  162. }
复制代码


运行编译即可启动 WebAPI 并在其他项目中调用了。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

0 个回复

您需要登录后才可以回帖 登录 | 立即注册
返回顶部