LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

C#WinForm實現WebApi接口服務

admin
2025年7月5日 10:19 本文熱度 123

在項目中經常會用到各種通訊方式,現介紹一下WinForm實現WebApi接口服務,不依賴IIS宿主;編碼道路雖然枯燥,只要我們堅定信念;時光會看見你的成長,也終將不負你的努力。↖(^ω^)↗

一、效果展示
啟動服務
接收數據
Postman發送數據
整體效果
二、功能設計
VS2017界面設計

NuGet安裝Microsoft.AspNet.WebApi.OwinSelfHost

安裝完成
IP、端口配置
三、核心代碼

請求路由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<stringobject> dic = new Dictionary<stringobject>();            try {                //將接收到的信息賦給事件類中Message屬性                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 { getset; }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}");
//新建OWINTriggerEvent類實例,并返回被調用方使用獲取里面的message和infoEvent事件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("服務已停止");}
// 跨線程安全更新UIprivate 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)規范實現?

以下是其主要特點和用法:

  1. ?核心功能?
  • 允許Web API脫離IIS運行,可在控制臺應用、Windows服務等環境中托管?
  • 使用HttpListener作為底層HTTP服務器?
  • 支持完整的Web API功能,包括路由、控制器、過濾器等?
  1. ?安裝方式?
    通過NuGet包管理器控制臺執行命令:
textCopy Code

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

這會自動安裝相關依賴包,包括Microsoft.Owin.Host.HttpListener和Microsoft.AspNet.WebApi.Owin?

  1. ?基本配置步驟?
  • 創建控制臺應用程序項目(.NET Framework 4.0+) ?
  • 添加Startup類配置Web API路由?
  • 在Program.cs中啟動OWIN宿主?
  1. ?典型應用場景?
  • 開發輕量級API服務?
  • 在WinForm程序中集成Web API?
  • 需要跨平臺部署的解決方案?
  1. ?優勢比較?
  • 比傳統IIS托管更輕量?
  • 比HttpSelfHost更靈活(支持中間件管道)
  • 支持靜態文件服務等擴展功能?


閱讀原文:原文鏈接


該文章在 2025/7/7 11:43:43 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
这里只有精品99久久 | 亚洲一区二区精品久久AV | 亚洲欧美日韩精品专区在线插放免费 | 久久精品国产欧美日韩亚洲 | 天天视频黄在线免费观看 | 在线中文字幕亚洲第一 |