C#WinForm实现WebApi接口服务
|
admin
2025年7月5日 10:19
本文热度 1185
|
在项目中经常会用到各种通讯方式,现介绍一下WinForm实现WebApi接口服务,不依赖IIS宿主;编码道路虽然枯燥,只要我们坚定信念;时光会看见你的成长,也终将不负你的努力。↖(^ω^)↗
NuGet安装Microsoft.AspNet.WebApi.OwinSelfHost
请求路由Startup.cs
using Owin;using System;using System.Net.Http.Headers;using System.Web.Http;
namespace FilterDemo{ class Startup { public void Configuration(IAppBuilder appBuilder) { try { HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); appBuilder.UseWebApi(config); } catch (Exception ex) { throw ex; } } }}
接口方法HomeController.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Web.Http;
namespace FilterDemo{ public class HomeController : ApiController { [HttpGet] public IHttpActionResult Get(int address) { string str = "123466"; return Json(str); } [HttpPost] public IHttpActionResult Post([FromBody] List<string> values) { Dictionary<string, object> dic = new Dictionary<string, object>(); try { FormMain.TriggerEvent.Message = values; FormMain.TriggerEvent.OnMessage();
dic.Add("flag", true); dic.Add("msg", "成功"); } catch(Exception ex) { dic.Add("flag", false); dic.Add("msg", ex.Message); } return Json(dic); } [HttpPut] public IHttpActionResult Put(int id, string value) { string str = "123466"; return Json(str); } [HttpDelete] public IHttpActionResult Delete(int id) { string str = "123466"; return Json(str); } }}
启动WebApi接口服务
#region WebApi接口服务public static OWINTriggerEvent TriggerEvent { get; set; }private IDisposable _webApp;private string BaseUrl = "http://192.168.200.84:2000";
private void StartServer(){string serverIp = ConfigurationManager.AppSettings["ServerIP"];string serverPort = ConfigurationManager.AppSettings["ServerPort"]; BaseUrl = $"http://{serverIp}:{serverPort}";
_webApp = WebApp.Start<Startup>(BaseUrl); AppendLog($"服务已启动: {BaseUrl}");
var triggerEvent = new OWINTriggerEvent(); TriggerEvent = triggerEvent; TriggerEvent.infoEvent += TriggerEvent_infoEvent;}
private void TriggerEvent_infoEvent(object sender, EventArgs e){try { List<string> msgList = TriggerEvent.Message; AppendLog("接收到信息:"+ JsonConvert.SerializeObject(msgList));foreach (var item in msgList) { loadPcdToImage(item); AppendLog("处理点云文件:" + item); } }catch (Exception ex) {throw; }}
private void StopServer(){ _webApp?.Dispose(); AppendLog("服务已停止");}
private void AppendLog(string message){ DateTime d = DateTime.Now;string dateStr = d.ToString("yyyy-MM-dd HH:mm:ss:fff");
if (rtbLog.InvokeRequired) rtbLog.BeginInvoke(new Action(() => rtbLog.AppendText(dateStr + " " + message + "\r\n")));else rtbLog.AppendText(dateStr + " " + message + "\r\n");}#endregion
Microsoft.AspNet.WebApi.OwinSelfHost是一个用于在非IIS环境下自托管ASP.NET Web API的NuGet包,它基于OWIN(Open Web Interface for .NET)规范实现。
以下是其主要特点和用法:
- 允许Web API脱离IIS运行,可在控制台应用、Windows服务等环境中托管
- 使用HttpListener作为底层HTTP服务器
- 支持完整的Web API功能,包括路由、控制器、过滤器等
- 安装方式
通过NuGet包管理器控制台执行命令:
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
这会自动安装相关依赖包,包括Microsoft.Owin.Host.HttpListener和Microsoft.AspNet.WebApi.Owin。
- 创建控制台应用程序项目(.NET Framework 4.0+)
- 比HttpSelfHost更灵活(支持中间件管道)
阅读原文:原文链接
该文章在 2025/7/7 11:43:43 编辑过