winform桌面程序如何调用后台API的方法(一)
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
每当进行winform桌面程序开发时,为了实现项目之间的代码复用,通常会将一些通用的方法封装成动态库(.dll)。但是这样也存在一个问题,假设将方法A方法封装成动态库MyDll后,项目Project1引用了MyDll,可以使用A方法;在项目Project2引用MyDll使用A方法时,发现A方法有bug,并对A方法进行修复。此时,Project1使用的方法A仍然存在bug,需要重新引用最新的MyDll才能修复A的bug。那么,是否有更好的解决方法,在Project2修复完成时,Project1引用的方法A也同步修复呢?
提示:以下是本篇文章正文内容,下面案例可供参考
一、如何解决?
现在我给大家介绍的,就是如何使用winform调用后台的API
二、使用步骤
步骤一:构建后台API
- 开发工具:VS2019
- 目标框架:.net core 3.1
- 先在后台写一个简单的方法GetDateTime,用于winform端进行调用。
代码如下(GetDateTime):
using Agreement.Business.System;
using Agreement.Entity.Enum;
using Agreement.Entity.Models.AgreementEntity;
using log4net;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace tokendemo.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class MyTestDemoController : CommServers
{
private readonly ILog _logger;
public MyTestDemoController()
{
_logger = LogManager.GetLogger(typeof(MyTestDemoController));
}
[HttpGet]
public async Task<TData> GetDateTime()
{
string strResult= "Beijing Time:" + DateTime.Now.ToString();
return ReturnObj<bool>(ResultEnum.Sucess, true, strResult);
}
}
}
4.为了将返回值进行统一,封装一个CommServers.cs类,用于赋值返回,需要引用类TData.cs和枚举ResultEnum.cs:
代码如下(CommServers.cs):
using Agreement.Entity.Enum;
using Agreement.Entity.Models.AgreementEntity;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Agreement.Business.System
{
public class CommServers
{
/// <summary>
/// 构造返回结果
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="result"></param>
/// <param name="data"></param>
/// <param name="mesage"></param>
/// <returns></returns>
public TData<T> ReturnObj<T>(ResultEnum result, T data, string mesage)
{
TData<T> obj = new TData<T>();
obj.Result = result;
obj.Data = data;
obj.TotalCount = 1;
obj.Message = mesage;
return obj;
}
}
}
5.第(4)点需要引用类TData.cs和枚举ResultEnum.cs
代码如下(TData.cs):
using Agreement.Entity.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Agreement.Entity.Models.AgreementEntity
{
public class TData
{
/// <summary>
/// 操作结果,Result为1代表成功,0代表失败,其他的验证返回结果,可根据需要设置
/// </summary>
public ResultEnum Result { get; set; }
/// <summary>
/// 提示信息或异常信息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 扩展Message
/// </summary>
public string Description { get; set; }
}
public class TData<T> : TData
{
/// <summary>
/// 列表的记录数
/// </summary>
public int TotalCount { get; set; }
/// <summary>
/// 数据
/// </summary>
public T Data { get; set; }
}
}
代码如下(ResultEnum.cs):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
namespace Agreement.Entity.Enum
{
/// <summary>
/// 操作结果,Result为1代表成功,0代表失败,其他的验证返回结果,可根据需要设置
/// </summary>
public enum ResultEnum
{
/// <summary>
/// 成功
/// </summary>
[Description("成功")]
Sucess = 1,
/// <summary>
/// 失败
/// </summary>
[Description("失败")]
Faill = 0
}
}
运行后,先在后台测试方法是否可用,如下图:
步骤二:构建后台API
- 开发工具:VS2019
- 目标框架:.net Framework 4.7.2
- 先创建一个简单的winform程序,并添加一个简单的测试按钮,如下图:
4. 在项目通过NutGet程序包,添加Newtonsoft.Json,操作步骤如下图:
5. 完成Newtonsoft.Json程序包的安装之后,新建两个类,HttpReuestUtility.cs(将和后台通讯的方法封装到这个类中)和JsonObject.cs(主要将后台的通讯结果进行封装)。
代码如下(HttpReuestUtility.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
namespace JasonHelp
{
public class HttpReuestUtility
{
/// <summary>
/// 发送jason到服务器
/// </summary>
/// <param name="SendDate"></param>
/// <param name="InterfaceName"></param>
/// <returns></returns>
public static JsonObject GetResponseData(string SendDate, string InterfaceName)
{
JsonObject reJson = new JsonObject();
try
{
if (SendDate == "")
{
SendDate = "{}";
}
byte[] bytes = Encoding.UTF8.GetBytes(SendDate);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InterfaceName);
request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";
//request.Accept = "text/plain";
request.ContentType = "application/json";
request.Accept = "application/json";
request.ContentLength = bytes.Length;
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
//声明一个HttpWebRequest请求
request.Timeout = 60000;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;
StreamReader streamReader = new StreamReader(streamReceive, encoding);
string strResult = streamReader.ReadToEnd();
streamReceive.Dispose();
streamReader.Dispose();
JObject JsonResult= JObject.Parse(strResult);
int isSuccess = JsonResult["result"].Value<int>();
string Result = JsonResult["message"].Value<string>();
//JArray jar = JArray.Parse(JsonResult["Data"].ToString());
reJson.isSuccess = isSuccess;
reJson.Result = Result;
reJson.Data = JsonResult["data"];
return reJson;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 发送jason到服务器
/// </summary>
/// <param name="SendDate"></param>
/// <param name="InterfaceName"></param>
/// <returns></returns>
public static JsonObject GetResponseDataByGet(string InterfaceName)
{
JsonObject reJson = new JsonObject();
try
{
// byte[] bytes = Encoding.UTF8.GetBytes(SendDate);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InterfaceName);
request.Method = "GET";
//request.ContentType = "application/x-www-form-urlencoded";
//request.Accept = "text/plain";
//request.ContentType = "application/json";
//request.Accept = "application/json";
//request.ContentLength = bytes.Length;
//Stream reqstream = request.GetRequestStream();
// reqstream.Write(bytes, 0, bytes.Length);
//声明一个HttpWebRequest请求
request.Timeout = 60000;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;
StreamReader streamReader = new StreamReader(streamReceive, encoding);
string strResult = streamReader.ReadToEnd();
streamReceive.Dispose();
streamReader.Dispose();
JObject JsonResult = JObject.Parse(strResult);
int isSuccess = JsonResult["result"].Value<int>();
string Result = JsonResult["message"].Value<string>();
//JArray jar = JArray.Parse(JsonResult["Data"].ToString());
reJson.isSuccess = isSuccess;
reJson.Result = Result;
reJson.Data = JsonResult["data"];
return reJson;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
代码如下(JsonObject.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace JasonHelp
{
public class JsonObject
{
private int _isSuccess = 0;
private string _Result = "";
//private JArray _Data = new JArray();
public object _Data = new object();
public JsonObject()
{
_isSuccess =0;
_Result = "";
_Data = null;
}
/// <summary>
/// 是否成功
/// </summary>
public int isSuccess
{
set { _isSuccess = value; }
get { return _isSuccess; }
}
/// <summary>
///结果
/// </summary>
public string Result
{
set { _Result = value; }
get { return _Result; }
}
/// <summary>
///返回数据
/// </summary>
public object Data
{
set { _Data = value; }
get { return _Data; }
}
}
}
6. 在新建的测试按钮,添加点击事件。
代码如下(按钮事件):
/// <summary>
/// 调用API GetDateTime 按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetTime_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
try
{
string strMessage = "";
JsonObject reJson = new JsonObject();
//后台地址
string strInterFace = "http://localhost:3252/MyTestDemo/GetDateTime";
reJson = HttpReuestUtility.GetResponseDataByGet(strInterFace);
if (reJson != null)
{
if (reJson.isSuccess == 1)//获取成功
{
strMessage = reJson.Result.ToString();
sb.AppendLine("结论:成功");
sb.AppendLine("结果:" + strMessage);
}
else
{
strMessage = reJson.Result.ToString();
sb.AppendLine("结论:失败");
sb.AppendLine("结果:" + strMessage);
}
}
else
{
strMessage = "和结果判定服务器通讯失败";
sb.AppendLine("结论:失败");
sb.AppendLine("结果:" + strMessage);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally {
this.richMessage.Text = sb.ToString();
}
}
步骤三:效果展示
- 先运行后台端服务
2.运行winform桌面程序后,点击调用API。
三、总结
以上就是今天要讲的内容,本文仅仅通过一个简单Demo,介绍了winform桌面程序如何调用后台API接口,方便大家参考使用。