WinForm 使用 RestSharp 实现接口的增、删、改、查

参考

环境

  1. WinForm 环境

    软件/系统 版本 说明
    Windows windows 10 专业版 22H2 64 位操作系统, 基于 x64 的处理器
    Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.13.6
    .NET Framework 4.8
    RestSharp 112.1.0 项目依赖
    Newtonsoft.Json 13.0.3 项目依赖
  2. ASP.NET Core 后端接口环境

    软件/系统 版本 说明
    Windows windows 10 专业版 22H2 64 位操作系统, 基于 x64 的处理器
    Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.13.6
    .NET SDK 6.0
    Microsoft.EntityFrameworkCore.SqlServer 7.0.20 项目依赖,7.x 版本兼容 .net 6.0
    Microsoft.EntityFrameworkCore.Design 7.0.20 项目依赖
    Microsoft.EntityFrameworkCore.Tools 7.0.20 项目依赖
    SQL Server Management Studio 20.2.37.0
    Windows Server Windows Server 2019 Standard Evaluation (10.0) 服务器
    SQL Server Microsoft SQL Server 2019 Enterprise Edition 服务器

预览

image

客户端代码

  1. Form1.cs
    using RestSharp;
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using Newtonsoft.Json;
    using System.Diagnostics;
    using System.Net;
    
    namespace RestSharp网络请求demo
    {
    	public partial class Form1 : Form
    	{
    		public Form1()
    		{
    			InitializeComponent();
    		}
    
    		private void tableLayoutPanel2_Paint(object sender, PaintEventArgs e)
    		{
    
    		}
    		/// <summary>
    		/// 获取列表
    		/// </summary>
    		/// <param name="sender"></param>
    		/// <param name="e"></param>
    		private async void GETListButton_Click(object sender, EventArgs e)
    		{
    			var options = new RestClientOptions("http://localhost:5039/api/students")
    			{
    				//Authenticator = new HttpBasicAuthenticator("username", "password")
    			};
    			using (var client = new RestClient(options))
    			{
    				var request = new RestRequest("");
    				//request.AddHeader("Content-Type", "application/json");
    				RestResponse response = response = await client.ExecuteGetAsync(request);
    				Debug.WriteLine((int)response.StatusCode);
    				if (response.StatusCode != HttpStatusCode.OK)
    				{
    					Debug.WriteLine(response.Content);
    					throw new Exception("响应码错误");
    				}
    				this.responseTextBox.Text = response.Content;
    				var obj = JsonConvert.DeserializeObject<List<Student>>(response.Content);
    				obj.ForEach((item) => Debug.WriteLine(item.Name));
    			}
    		}
    
    		private async void GETRowButton5_Click(object sender, EventArgs e)
    		{
    			var options = new RestClientOptions("http://localhost:5039/api/students")
    			{
    				//Authenticator = new HttpBasicAuthenticator("username", "password")
    			};
    			using (var client = new RestClient(options))
    			{
    				var request = new RestRequest("1");
    				//request.AddHeader("Content-Type", "application/json");
    				//
    				RestResponse response = response = await client.ExecuteGetAsync(request);
    				Debug.WriteLine((int)response.StatusCode);
    				if (response.StatusCode != HttpStatusCode.OK)
    				{
    					Debug.WriteLine(response.Content);
    					throw new Exception("响应码错误");
    				}
    				this.responseTextBox.Text = response.Content;
    				var obj = JsonConvert.DeserializeObject<Student>(response.Content);
    				Debug.WriteLine(obj.Name);
    			}
    		}
    
    		private async void POSTButton_Click(object sender, EventArgs e)
    		{
    			var options = new RestClientOptions("http://localhost:5039/api/students")
    			{
    				//Authenticator = new HttpBasicAuthenticator("username", "password")
    			};
    			using (var client = new RestClient(options))
    			{
    				var request = new RestRequest("");
    				request.AddHeader("Content-Type", "application/json");
    				//
    				request.AddJsonBody(new { 
    					Name = "张三",
    					Age = 18,
    					ClassRoomId = 6
    				});
    				//
    				RestResponse response = response = await client.ExecutePostAsync(request);
    				Debug.WriteLine((int)response.StatusCode);
    				if (response.StatusCode != HttpStatusCode.Created)
    				{
    					Debug.WriteLine(response.Content);
    					throw new Exception("响应码错误");
    				}
    				this.responseTextBox.Text = response.Content;
    				var obj = JsonConvert.DeserializeObject<Student>(response.Content);
    				Debug.WriteLine(obj.Name);
    			}
    		}
    
    		private async void PUTButton_Click(object sender, EventArgs e)
    		{
    			var options = new RestClientOptions("http://localhost:5039/api/students")
    			{
    				//Authenticator = new HttpBasicAuthenticator("username", "password")
    			};
    			using (var client = new RestClient(options))
    			{
    				var request = new RestRequest("2");
    				request.AddHeader("Content-Type", "application/json");
    				//
    				request.AddJsonBody(new
    				{
    					Id = 2,
    					Name = "张三",
    					Age = 18,
    					ClassRoomId = 6
    				});
    				//
    				RestResponse response = response = await client.ExecutePutAsync(request);
    				Debug.WriteLine((int)response.StatusCode);
    				if (response.StatusCode != HttpStatusCode.NoContent)
    				{
    					throw new Exception("响应码错误");
    				}
    				Debug.WriteLine(response.Content);
    				this.responseTextBox.Text = "修改成功";
    			}
    		}
    
    		private async void DELETEButton_Click(object sender, EventArgs e)
    		{
    			var options = new RestClientOptions("http://localhost:5039/api/students")
    			{
    				//Authenticator = new HttpBasicAuthenticator("username", "password")
    			};
    			using (var client = new RestClient(options))
    			{
    				var request = new RestRequest("38");
    				request.AddHeader("Content-Type", "application/json");
    				//
    				RestResponse response = response = await client.ExecuteDeleteAsync(request);
    				Debug.WriteLine((int)response.StatusCode);
    				if (response.StatusCode != HttpStatusCode.NoContent)
    				{
    					throw new Exception("响应码错误");
    				}
    				Debug.WriteLine(response.Content);
    				this.responseTextBox.Text = "删除成功";
    			}
    			;
    		}
    	}
    	public class Student
    	{
    		public int Id { get; set; }
    
    		/// <summary>
    		/// 学生姓名
    		/// </summary>
    		public string Name { get; set; }
    
    		/// <summary>
    		/// 年龄
    		/// </summary>
    		public byte? Age { get; set; }
    
    		/// <summary>
    		/// 班级Id
    		/// </summary>
    		public int? ClassRoomId { get; set; }
    	}
    }
    
    
  2. Form1.Designer.cs
    namespace RestSharp网络请求demo
    {
    	partial class Form1
    	{
    		/// <summary>
    		/// 必需的设计器变量。
    		/// </summary>
    		private System.ComponentModel.IContainer components = null;
    
    		/// <summary>
    		/// 清理所有正在使用的资源。
    		/// </summary>
    		/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
    		protected override void Dispose(bool disposing)
    		{
    			if (disposing && (components != null))
    			{
    				components.Dispose();
    			}
    			base.Dispose(disposing);
    		}
    
    		#region Windows 窗体设计器生成的代码
    
    		/// <summary>
    		/// 设计器支持所需的方法 - 不要修改
    		/// 使用代码编辑器修改此方法的内容。
    		/// </summary>
    		private void InitializeComponent()
    		{
    			this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
    			this.groupBox2 = new System.Windows.Forms.GroupBox();
    			this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
    			this.button1 = new System.Windows.Forms.Button();
    			this.button5 = new System.Windows.Forms.Button();
    			this.button2 = new System.Windows.Forms.Button();
    			this.button3 = new System.Windows.Forms.Button();
    			this.button4 = new System.Windows.Forms.Button();
    			this.groupBox1 = new System.Windows.Forms.GroupBox();
    			this.responseTextBox = new System.Windows.Forms.TextBox();
    			this.tableLayoutPanel1.SuspendLayout();
    			this.groupBox2.SuspendLayout();
    			this.flowLayoutPanel1.SuspendLayout();
    			this.groupBox1.SuspendLayout();
    			this.SuspendLayout();
    			// 
    			// tableLayoutPanel1
    			// 
    			this.tableLayoutPanel1.ColumnCount = 3;
    			this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 12.5F));
    			this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 75F));
    			this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 12.5F));
    			this.tableLayoutPanel1.Controls.Add(this.groupBox2, 1, 0);
    			this.tableLayoutPanel1.Controls.Add(this.groupBox1, 1, 1);
    			this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
    			this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
    			this.tableLayoutPanel1.Name = "tableLayoutPanel1";
    			this.tableLayoutPanel1.RowCount = 2;
    			this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 300F));
    			this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
    			this.tableLayoutPanel1.Size = new System.Drawing.Size(859, 759);
    			this.tableLayoutPanel1.TabIndex = 0;
    			// 
    			// groupBox2
    			// 
    			this.groupBox2.Controls.Add(this.flowLayoutPanel1);
    			this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
    			this.groupBox2.Location = new System.Drawing.Point(110, 3);
    			this.groupBox2.Name = "groupBox2";
    			this.groupBox2.Size = new System.Drawing.Size(638, 294);
    			this.groupBox2.TabIndex = 2;
    			this.groupBox2.TabStop = false;
    			this.groupBox2.Text = "操作";
    			// 
    			// flowLayoutPanel1
    			// 
    			this.flowLayoutPanel1.Controls.Add(this.button1);
    			this.flowLayoutPanel1.Controls.Add(this.button5);
    			this.flowLayoutPanel1.Controls.Add(this.button2);
    			this.flowLayoutPanel1.Controls.Add(this.button3);
    			this.flowLayoutPanel1.Controls.Add(this.button4);
    			this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
    			this.flowLayoutPanel1.Location = new System.Drawing.Point(196, 20);
    			this.flowLayoutPanel1.Name = "flowLayoutPanel1";
    			this.flowLayoutPanel1.Size = new System.Drawing.Size(202, 252);
    			this.flowLayoutPanel1.TabIndex = 1;
    			// 
    			// button1
    			// 
    			this.button1.Location = new System.Drawing.Point(3, 3);
    			this.button1.Name = "button1";
    			this.button1.Size = new System.Drawing.Size(197, 39);
    			this.button1.TabIndex = 5;
    			this.button1.Text = "获取列表";
    			this.button1.UseVisualStyleBackColor = true;
    			this.button1.Click += new System.EventHandler(this.GETListButton_Click);
    			// 
    			// button5
    			// 
    			this.button5.Location = new System.Drawing.Point(3, 48);
    			this.button5.Name = "button5";
    			this.button5.Size = new System.Drawing.Size(197, 39);
    			this.button5.TabIndex = 6;
    			this.button5.Text = "获取某行";
    			this.button5.UseVisualStyleBackColor = true;
    			this.button5.Click += new System.EventHandler(this.GETRowButton5_Click);
    			// 
    			// button2
    			// 
    			this.button2.Location = new System.Drawing.Point(3, 93);
    			this.button2.Name = "button2";
    			this.button2.Size = new System.Drawing.Size(197, 39);
    			this.button2.TabIndex = 6;
    			this.button2.Text = "添加";
    			this.button2.UseVisualStyleBackColor = true;
    			this.button2.Click += new System.EventHandler(this.POSTButton_Click);
    			// 
    			// button3
    			// 
    			this.button3.Location = new System.Drawing.Point(3, 138);
    			this.button3.Name = "button3";
    			this.button3.Size = new System.Drawing.Size(197, 39);
    			this.button3.TabIndex = 7;
    			this.button3.Text = "修改";
    			this.button3.UseVisualStyleBackColor = true;
    			this.button3.Click += new System.EventHandler(this.PUTButton_Click);
    			// 
    			// button4
    			// 
    			this.button4.Location = new System.Drawing.Point(3, 183);
    			this.button4.Name = "button4";
    			this.button4.Size = new System.Drawing.Size(197, 39);
    			this.button4.TabIndex = 8;
    			this.button4.Text = "删除";
    			this.button4.UseVisualStyleBackColor = true;
    			this.button4.Click += new System.EventHandler(this.DELETEButton_Click);
    			// 
    			// groupBox1
    			// 
    			this.groupBox1.Controls.Add(this.responseTextBox);
    			this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
    			this.groupBox1.Location = new System.Drawing.Point(110, 303);
    			this.groupBox1.Name = "groupBox1";
    			this.groupBox1.Size = new System.Drawing.Size(638, 453);
    			this.groupBox1.TabIndex = 1;
    			this.groupBox1.TabStop = false;
    			this.groupBox1.Text = "响应内容";
    			// 
    			// responseTextBox
    			// 
    			this.responseTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
    			this.responseTextBox.Location = new System.Drawing.Point(3, 17);
    			this.responseTextBox.Multiline = true;
    			this.responseTextBox.Name = "responseTextBox";
    			this.responseTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
    			this.responseTextBox.Size = new System.Drawing.Size(632, 433);
    			this.responseTextBox.TabIndex = 0;
    			// 
    			// Form1
    			// 
    			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
    			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    			this.ClientSize = new System.Drawing.Size(859, 759);
    			this.Controls.Add(this.tableLayoutPanel1);
    			this.Name = "Form1";
    			this.Text = "Form1";
    			this.tableLayoutPanel1.ResumeLayout(false);
    			this.groupBox2.ResumeLayout(false);
    			this.flowLayoutPanel1.ResumeLayout(false);
    			this.groupBox1.ResumeLayout(false);
    			this.groupBox1.PerformLayout();
    			this.ResumeLayout(false);
    
    		}
    
    		#endregion
    
    		private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
    		private System.Windows.Forms.Button button1;
    		private System.Windows.Forms.Button button2;
    		private System.Windows.Forms.Button button3;
    		private System.Windows.Forms.GroupBox groupBox1;
    		private System.Windows.Forms.TextBox responseTextBox;
    		private System.Windows.Forms.GroupBox groupBox2;
    		private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
    		private System.Windows.Forms.Button button5;
    		private System.Windows.Forms.Button button4;
    	}
    }
    
    
    

后端接口代码

由于后端接口不在本文主要讲述内容内,仅展示对应控制器接口代码

  1. StudentsController.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using WebApplication1.Data;
    using WebApplication1.Models;
    
    namespace WebApplication1.Controllers
    {
    	// [controller]会自动替换为对应控制器名字,无需调整
    	[Route("api/[controller]")]
    	[ApiController]
    	public class StudentsController : ControllerBase
    	{
    		private readonly DBContent _context;
    
    		public StudentsController(DBContent context)
    		{
    			_context = context;
    		}
    
    		// GET: api/Students
    		[HttpGet]
    		public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
    		{
    		  if (_context.Students == null)
    		  {
    			  return NotFound();
    		  }
    			return await _context.Students.ToListAsync();
    		}
    
    		// GET: api/Students/5
    		[HttpGet("{id}")]
    		public async Task<ActionResult<Student>> GetStudent(int id)
    		{
    		  if (_context.Students == null)
    		  {
    			  return NotFound();
    		  }
    			var student = await _context.Students.FindAsync(id);
    
    			if (student == null)
    			{
    				return NotFound();
    			}
    
    			return student;
    		}
    
    		// PUT: api/Students/5
    		// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
    		[HttpPut("{id}")]
    		public async Task<IActionResult> PutStudent(int id, Student student)
    		{
    			if (id != student.Id)
    			{
    				return BadRequest();
    			}
    
    			_context.Entry(student).State = EntityState.Modified;
    
    			try
    			{
    				await _context.SaveChangesAsync();
    			}
    			catch (DbUpdateConcurrencyException)
    			{
    				if (!StudentExists(id))
    				{
    					return NotFound();
    				}
    				else
    				{
    					throw;
    				}
    			}
    
    			return NoContent();
    		}
    
    		// POST: api/Students
    		// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
    		[HttpPost]
    		public async Task<ActionResult<Student>> PostStudent(Student student)
    		{
    		  if (_context.Students == null)
    		  {
    			  return Problem("Entity set 'DBContent.Students'  is null.");
    		  }
    			_context.Students.Add(student);
    			await _context.SaveChangesAsync();
    
    			return CreatedAtAction("GetStudent", new { id = student.Id }, student);
    		}
    
    		// DELETE: api/Students/5
    		[HttpDelete("{id}")]
    		public async Task<IActionResult> DeleteStudent(int id)
    		{
    			if (_context.Students == null)
    			{
    				return NotFound();
    			}
    			var student = await _context.Students.FindAsync(id);
    			if (student == null)
    			{
    				return NotFound();
    			}
    
    			_context.Students.Remove(student);
    			await _context.SaveChangesAsync();
    
    			return NoContent();
    		}
    
    		private bool StudentExists(int id)
    		{
    			return (_context.Students?.Any(e => e.Id == id)).GetValueOrDefault();
    		}
    	}
    }
    
posted @ 2025-05-20 00:28  夏秋初  阅读(87)  评论(0)    收藏  举报