VB 小源码
读完需要
21
分钟
速读仅需 7 分钟
UI 效果图(辣鸡图见谅)
本篇文章是接着上期的《VB.NET 结合 B4A 开发进行远程查图报共上传数据功能》的一个延展性,本期主要介绍 WebApi 自托管于 WinForm 程序上的对外作为数据服务接口的一个简单示例!想跟深入研究的大佬们自行度娘咯;本文只做个抛砖引玉;
一、首先添加.NET WebApi 的相关 DLL
下面图列是介绍在 NuGET 上安装相关 DLL 的图例
二、给程序赋予管理员权限(新技能哦!各位看官)
配置文件长这样啦
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
</application>
</compatibility>
</assembly>
三、开始敲代码了哦
''' <summary>
''' WebApi服务类
''' </summary>
Public Class ClassHttpService
Implements IDisposable
''' <summary>
''' 服务端口
''' </summary>
''' <returns></returns>
Public Property Port As Integer
''' <summary>
''' 服务IP
''' </summary>
''' <returns></returns>
Public Property IP As String
''' <summary>
''' 自托管服务对象
''' </summary>
Private ReadOnly SelfHostServer As HttpSelfHostServer
''' <summary>
''' 初始化WebApi服务类
''' </summary>
''' <param name="IP">本机IP地址</param>
''' <param name="port">开放的端口</param>
Public Sub New(IP As String, port As Integer)
Me.Port = port
Me.IP = IP
Dim WebCongfig As HttpSelfHostConfiguration = New HttpSelfHostConfiguration($"http://{Me.IP}:{Me.Port}")
WebCongfig.MapHttpAttributeRoutes()
WebCongfig.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}")
SelfHostServer = New HttpSelfHostServer(WebCongfig)
End Sub
''' <summary>
''' 启动WebApi服务
''' </summary>
''' <returns></returns>
Public Function StartHttpServer() As Task
Return SelfHostServer.OpenAsync()
End Function
''' <summary>
''' 关闭WebApi服务
''' </summary>
''' <returns></returns>
Public Function CloseHttpServer() As Task
Return SelfHostServer.CloseAsync()
End Function
''' <summary>
''' 释放对象
''' </summary>
Public Sub Dispose() Implements IDisposable.Dispose
SelfHostServer.Dispose()
End Sub
End Class
''' <summary>
''' WebApi控制器
''' </summary>
<RoutePrefix("api/home")>
Public Class HomeController
Inherits ApiController
''' <summary>
''' 自定义事件用于与窗口交互
''' </summary>
Public Shared Event Msg As EventHandler(Of String)
''' <summary>
''' GET请求测试
''' 访问地址: http://[你的IP]:[端口]/api/home
''' </summary>
''' <returns></returns>
<Route("")>
<HttpGet>
Public Function GetPrintJson() As IHttpActionResult
''触发消息事件
RaiseEvent Msg(Nothing, $"[{Now}][GET请求测试][{Request.RequestUri.AbsoluteUri}][微信公众号:VB小源码]")
''返回结果给前端
Return Json(New With {
.Name = "VB小源码",
.Message = $"你好啊!小可爱们...",
.Func = "GET请求测试..."
})
End Function
''' <summary>
''' POST请求测试
''' 访问地址: http://[你的IP]:[端口]/api/home
''' </summary>
''' <returns></returns>
<Route("")>
<HttpPost>
Public Function PostPrintJson() As IHttpActionResult
''触发消息事件
RaiseEvent Msg(Nothing, $"[{Now}][POST请求测试][{Request.RequestUri.AbsoluteUri}][微信公众号:VB小源码]")
'返回结果给前端
Return Json(New With {
.Name = "VB小源码",
.Message = $"你好啊!小可爱们...",
.Func = "POST请求测试..."
})
End Function
End Class
`
Public Class Form_main
Private SHttp As ClassHttpService = Nothing
Public Sub New()
InitializeComponent()
''注册窗体交互事件
AddHandler HomeController.Msg, New EventHandler(Of String)(AddressOf Out_log)
End Sub
''' <summary>
''' 启动服务
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
<Obsolete>
Private Sub Bt_StartServer_Click(sender As Object, e As EventArgs) Handles Bt_StartServer.Click
Dim IP As IPAddress = Dns.Resolve(Dns.GetHostName()).AddressList(0)
If SHttp Is Nothing Then
SHttp = New ClassHttpService(IP.ToString(), 8808)
End If
SHttp.CloseHttpServer()
SHttp.StartHttpServer()
Txt_log.AppendText("WebApi服务器已启动..." & vbCrLf)
End Sub
''' <summary>
''' 停止服务
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub Bt_StopServer_Click(sender As Object, e As EventArgs) Handles Bt_StopServer.Click
SHttp.CloseHttpServer()
SHttp.Dispose()
Txt_log.AppendText("WebApi服务器已关闭..." & vbCrLf)
End Sub
''' <summary>
''' 输出日志事件
''' </summary>
''' <param name="sender"></param>
''' <param name="msg"></param>
Sub Out_log(sender As Object, msg As String)
Txt_log.Invoke(Sub()
Txt_log.AppendText(msg & vbCrLf)
End Sub)
End Sub
Private Sub Form_main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TopMost = True
End Sub
End Class
四、完整代码
Imports System.Net
Imports System.Web.Http
Imports System.Web.Http.SelfHost
Public Class Form_main
Private SHttp As ClassHttpService = Nothing
Public Sub New()
InitializeComponent()
''注册窗体交互事件
AddHandler HomeController.Msg, New EventHandler(Of String)(AddressOf Out_log)
End Sub
''' <summary>
''' 启动服务
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
<Obsolete>
Private Sub Bt_StartServer_Click(sender As Object, e As EventArgs) Handles Bt_StartServer.Click
Dim IP As IPAddress = Dns.Resolve(Dns.GetHostName()).AddressList(0)
If SHttp Is Nothing Then
SHttp = New ClassHttpService(IP.ToString(), 8808)
End If
SHttp.CloseHttpServer()
SHttp.StartHttpServer()
Txt_log.AppendText("WebApi服务器已启动..." & vbCrLf)
End Sub
''' <summary>
''' 停止服务
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub Bt_StopServer_Click(sender As Object, e As EventArgs) Handles Bt_StopServer.Click
SHttp.CloseHttpServer()
SHttp.Dispose()
Txt_log.AppendText("WebApi服务器已关闭..." & vbCrLf)
End Sub
''' <summary>
''' 输出日志事件
''' </summary>
''' <param name="sender"></param>
''' <param name="msg"></param>
Sub Out_log(sender As Object, msg As String)
Txt_log.Invoke(Sub()
Txt_log.AppendText(msg & vbCrLf)
End Sub)
End Sub
Private Sub Form_main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TopMost = True
End Sub
End Class
''' <summary>
''' WebApi服务类
''' </summary>
Public Class ClassHttpService
Implements IDisposable
''' <summary>
''' 服务端口
''' </summary>
''' <returns></returns>
Public Property Port As Integer
''' <summary>
''' 服务IP
''' </summary>
''' <returns></returns>
Public Property IP As String
''' <summary>
''' 自托管服务对象
''' </summary>
Private ReadOnly SelfHostServer As HttpSelfHostServer
''' <summary>
''' 初始化WebApi服务类
''' </summary>
''' <param name="IP">本机IP地址</param>
''' <param name="port">开放的端口</param>
Public Sub New(IP As String, port As Integer)
Me.Port = port
Me.IP = IP
Dim WebCongfig As HttpSelfHostConfiguration = New HttpSelfHostConfiguration($"http://{Me.IP}:{Me.Port}")
WebCongfig.MapHttpAttributeRoutes()
WebCongfig.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}")
SelfHostServer = New HttpSelfHostServer(WebCongfig)
End Sub
''' <summary>
''' 启动WebApi服务
''' </summary>
''' <returns></returns>
Public Function StartHttpServer() As Task
Return SelfHostServer.OpenAsync()
End Function
''' <summary>
''' 关闭WebApi服务
''' </summary>
''' <returns></returns>
Public Function CloseHttpServer() As Task
Return SelfHostServer.CloseAsync()
End Function
''' <summary>
''' 释放对象
''' </summary>
Public Sub Dispose() Implements IDisposable.Dispose
SelfHostServer.Dispose()
End Sub
End Class
''' <summary>
''' WebApi控制器
''' </summary>
<RoutePrefix("api/home")>
Public Class HomeController
Inherits ApiController
''' <summary>
''' 自定义事件用于与窗口交互
''' </summary>
Public Shared Event Msg As EventHandler(Of String)
''' <summary>
''' GET请求测试
''' 访问地址: http://[你的IP]:[端口]/api/home
''' </summary>
''' <returns></returns>
<Route("")>
<HttpGet>
Public Function GetPrintJson() As IHttpActionResult
''触发消息事件
RaiseEvent Msg(Nothing, $"[{Now}][GET请求测试][{Request.RequestUri.AbsoluteUri}][微信公众号:VB小源码]")
''返回结果给前端
Return Json(New With {
.Name = "VB小源码",
.Message = $"你好啊!小可爱们...",
.Func = "GET请求测试..."
})
End Function
''' <summary>
''' POST请求测试
''' 访问地址: http://[你的IP]:[端口]/api/home
''' </summary>
''' <returns></returns>
<Route("")>
<HttpPost>
Public Function PostPrintJson() As IHttpActionResult
''触发消息事件
RaiseEvent Msg(Nothing, $"[{Now}][POST请求测试][{Request.RequestUri.AbsoluteUri}][微信公众号:VB小源码]")
'返回结果给前端
Return Json(New With {
.Name = "VB小源码",
.Message = $"你好啊!小可爱们...",
.Func = "POST请求测试..."
})
End Function
End Class
五、示例代码项目下载
https://vbee.lanzoui.com/imffkplc8ja