winform 通过http请求 web api 实现增删改查

1、创建数据库  教务数据库 =》学生信息


2、创建asp.net core webapi 

首先创建Asp.net core Web Api 项目(注意选择的C#),添加项目名称,创建项目

3、在2的基础上搭建三层架构


4、通过dapper的orm访问数据

首先在数据访问层安装dapper包,在ui层实现数据库连接

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DAL;
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;
using NLog.Extensions.Logging;

namespace StudentInfo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            DBHelper.ConnectionString = Configuration["ConnectionString"];
        }

        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.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.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

项目搭建好后,创建一个实体类(提示:需声明主键和连接的表名),在数据访问层实现数据访问,在业务逻辑层实现判断,判断成后后提交给UI层

using NPoco;
using System;
using System.Collections.Generic;
using System.Text;

namespace Model
{
    [TableName("StudentInfo")]
    [PrimaryKey("Sid",AutoIncrement =true)]
    public  class StudentInfo
    {
        public int Sid { get; set; }
        public string Sname { get; set; }
        public int Sage { get; set; }
        public string SPhone { get; set; }
    }
}
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionString": "Data Source=.;Initial Catalog=Student;Integrated Security=True",
   
  "AllowedHosts": "*"
}

在业务逻辑层调用数据访问层的方法

using DAL;
using DBAccess;
using Model;
using System;
using System.Collections.Generic;
using System.Text;

namespace BLL
{
   public class StudentBLL
    {/// <summary>
    /// 查询数据
    /// </summary>
    /// <returns></returns>
        public static List<StudentInfo> GetList()
        {

            return StudentDAL.GetList();
        }
        /// <summary>
        /// 根据id获取所对应 的数据
        /// </summary>
        /// <param name="SId"></param>
        /// <returns></returns>
        public static StudentInfo GetModel(int SId) => StudentDAL.GetModel(SId);
        /// <summary>
        /// 添加和修改
        /// </summary>
        /// <param name="student"></param>
        /// <returns></returns>
        public static ResultInfo Update(StudentInfo student)
        {
            if (student.Sid > 0)
            {


                if (StudentDAL.Update(student))
                {
                    return ReturnResult.ReturnSuccess("修改成功!");
                }
                else
                {
                    return ReturnResult.ReturnError("修改失败!");
                } }
            else 
                {
                if (StudentDAL.Insert(student))
                {
                    return ReturnResult.ReturnSuccess("添加成功!");
                }
                else
                {
                    return ReturnResult.ReturnError("添加失败!");
                }

            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Sid"></param>
        /// <returns></returns>
        public static ResultInfo Delete(int Sid)
        {
            if (StudentDAL.Delete(Sid))
            {
                return ReturnResult.ReturnSuccess("删除成功!");
            }
            else
            {
                return ReturnResult.ReturnError("删除失败!");
            }
        }
    }
}

在UI层调用业务逻辑层的方法,首先创建一个api控制器

然后实现方法的使用(注意:post方式传递数据需要加上Formbody,用来接收json数据)

using BLL;
using DBAccess;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentInfo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
  
    public class StudentController : ControllerBase
    {
        private readonly ILogger<StudentController> _logger;
        public StudentController(ILogger<StudentController> logger) 
        {
            _logger = logger;
        }
        //查询
        [HttpGet("GetList")]
        public List<Model.StudentInfo> GetList()
        {
            _logger.LogError("这是错误信息");
            _logger.LogDebug("这是调试信息");
            _logger.LogInformation("这是提示信息");
            return BLL.StudentBLL.GetList();
            
        }
        //修改和添加
        [HttpPost("UpdateStudent")]
        public ResultInfo UpdateStudent([FromBody] Model.StudentInfo model) => BLL.StudentBLL.Update(model);

      //删除
        [HttpPost("DeleteStudent")]  
        public ResultInfo DeleteStudent([FromBody] int Sid)
        {
            ResultInfo result = new ResultInfo();
            try
            {
                result= BLL.StudentBLL.Delete(Sid);
            }
            catch (Exception ex)
            {
                _logger.LogDebug(ex.Message);
            }
            return result;
        } 
        
        [HttpGet("GetModel/{SId}")]
        public Model.StudentInfo GetModel(int SId) => StudentBLL.GetModel(SId);
    }
}


5、创建winfrom项目

首先创建一个winform窗体和model类(model类和上面雷同,不做多余展示)

然后创建一个公共类(用来实现get和post请求的方法,winform 通过http请求 webapi)

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class HttpHelper
    {
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="statusCode"></param>
        /// <returns></returns>
        public static string PostResponse(string url, string postData, out string statusCode)
        {
            string result = string.Empty;
            //设置Http的正文
            HttpContent httpContent = new StringContent(postData);
            //设置Http的内容标头
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //设置Http的内容标头的字符
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                //异步Post
                HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
                //输出Http响应状态码
                statusCode = response.StatusCode.ToString();
                //确保Http响应成功
                if (response.IsSuccessStatusCode)
                {
                    //异步读取json
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }

        // 泛型:Post请求
        public static T PostResponse<T>(string url, string postData) where T : class, new()
        {
            T result = default(T);

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                    //Newtonsoft.Json
                    string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json);
                }
            }
            return result;
        }

        // 泛型:Get请求
        public static T GetResponse<T>(string url) where T : class, new()
        {
            T result = default(T);

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = httpClient.GetAsync(url).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                     string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json);
                }
            }
            return result;
        }

        // Get请求
        public static string PostResponse(string url)
        {
            string result = string.Empty;

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                var statusCode = response.StatusCode.ToString();

                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }
    }
}

创建一个类,用来连接api里的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class ApiList
    {
        public static string BaseApi = "https://localhost:44317/api/";
        public static string GetListStudent = "Student/GetList";
        public static string GetModelStudent = "Student/GetModel";
        public static string EditStudent = "Student/UpdateStudent";
        public static string DeleteStudent= "Student/DeleteStudent";
    }
}

创建一个类用来调用web api里的方法

using Common;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Business
{
    public  class StudentInfoBusiness
    {    
        string statusCode = string.Empty;
        public static List<Student> GetListStudent()
        {
            return JsonConvert.DeserializeObject<List<Student>>(HttpHelper.PostResponse(ApiList.BaseApi + ApiList.GetListStudent)); 
        }
        public static ResultInfo GetEditStudent(Student model)
        {
            return HttpHelper.PostResponse<ResultInfo>(ApiList.BaseApi + ApiList.EditStudent, JsonConvert.SerializeObject(model));
        }
        public static ResultInfo GetDelete(int sid)
        {
            return HttpHelper.PostResponse<ResultInfo>(ApiList.BaseApi + ApiList.DeleteStudent,JsonConvert.SerializeObject(sid));
        }
        public static ResultInfo GetEditStudent(int sid)
        { 
            return JsonConvert.DeserializeObject<ResultInfo>(HttpHelper.PostResponse(ApiList.BaseApi + ApiList.EditStudent));
        }
        public static Student GetModelStudent(int sid)
        {
           
            return  HttpHelper.GetResponse<Student>(ApiList.BaseApi + ApiList.GetModelStudent + "/" + sid);
        }
    }
}


6、通过winform项目访问api实现学生信息的增、删、改、查  

using Business;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common;

namespace StudentApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Bind();
        }
        //数据绑定到gridControl1
        public void Bind()
        {
            gridControl1.DataSource = StudentInfoBusiness.GetListStudent();
            gridControl1.RefreshDataSource();
        }
        //查询
        private void bar_Query_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Bind();
        }

        //添加
        private void bar_Add_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AddStudent eu = new AddStudent(0);
            eu.ShowDialog();
            Bind();

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bar_Delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (gridView1.FocusedRowHandle < 0) return;
            var Id = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Sid"));
            var Result = StudentInfoBusiness.GetDelete(Id);
            if (Result.State == (int)States.Success)
            {
                MessageBox.Show(Result.Msg);
            }
            Bind();
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bar_Edit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0)
            {
                MessageBox.Show("请选中一行数据再来操作吧!"); return;
            }
            var Id = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Sid"));
            EditStudent eu = new EditStudent(Id);
            eu.ShowDialog();
            Bind();
        }
    }
}

添加的实现:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Model;
using Business;
using Common;

namespace StudentApp
{
    public partial class AddStudent : DevExpress.XtraEditors.XtraForm
    {
        public int Id = 0;
        public AddStudent(int _Id = 0)
        {
            InitializeComponent();
            Id = _Id;
        }
        private void btnInsert_Click(object sender, EventArgs e)
        {
            Student student = new Student();
            student.Sid = Id;
            student.Sname = txtName.Text;
            student.Sage = Convert.ToInt32(txtAge.Text);
            student.SPhone = txtPhone.Text;
            var Rsult = StudentInfoBusiness.GetEditStudent(student);
            //MessageBox.Show(Rsult.Msg);
            if (Rsult.State == (int)States.Success)
            {
                MessageBox.Show(Rsult.Msg);
            }
            Close();
        }

    
    }
}

编辑的实现:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Business;
using Common;

namespace StudentApp
{
    public partial class EditStudent : DevExpress.XtraEditors.XtraForm
    {
        public int Id = 0;
        public EditStudent(int _Id)
        {
            InitializeComponent();
            Id = _Id;
        }

        private void btn_Edit_Click(object sender, EventArgs e)
        {
            var model = StudentInfoBusiness.GetModelStudent(Id);
            if (model != null)
            {
                model.Sid = Id;
                model.Sname = txtName.Text;
                model.Sage = Convert.ToInt32(txtAge.Text);
                model.SPhone = txtPhone.Text;

            }
            var Result = StudentInfoBusiness.GetEditStudent(model);
            if (Result.State == (int)States.Success)
            {
                MessageBox.Show(Result.Msg);
            }
            Close();
        }

        private void EditStudent_Load(object sender, EventArgs e)
        {
            var model = StudentInfoBusiness.GetModelStudent(Id);
            if (model != null)
            {
                txtName.Text = model.Sname;
                txtAge.Text = model.Sage.ToString();
                txtPhone.Text = model.SPhone;

            }
        }
    }
}

注:添加和编辑可写一个窗体里

 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值