前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >VB.NET WinForm自托管WebApi服务器(接上期的视频)

VB.NET WinForm自托管WebApi服务器(接上期的视频)

作者头像
一线编程
发布2021-06-25 21:40:00
2K0
发布2021-06-25 21:40:00
举报
文章被收录于专栏:办公魔盒

VB 小源码

读完需要

21

分钟

速读仅需 7 分钟

UI 效果图(辣鸡图见谅)

  本篇文章是接着上期的《VB.NET 结合 B4A 开发进行远程查图报共上传数据功能》的一个延展性,本期主要介绍 WebApi 自托管于 WinForm 程序上的对外作为数据服务接口的一个简单示例!想跟深入研究的大佬们自行度娘咯;本文只做个抛砖引玉;

一、首先添加.NET WebApi 的相关 DLL

  • Microsoft.AspNet.WebApi.Client
  • Microsoft.AspNet.WebApi.Core
  • Microsoft.AspNet.WebApi.SelfHost

下面图列是介绍在 NuGET 上安装相关 DLL 的图例

  • 1.1、打开 nuget

  • 1.2、搜索 webapi 相关 dll

  • 1.3、安装完成后,看下图

二、给程序赋予管理员权限(新技能哦!各位看官)

  • 2.1、右击项目,添加,新建项

  • 2.2、添加“应用程序清单文件“

  • 2.3、配置应用清单(看下图)

配置文件长这样啦

代码语言:javascript
复制

<?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>

  • 2.4、点击启动按钮,编译一次程序,这时会提示以管理员凭证启动,点击即可以管理员身份重启

三、开始敲代码了哦

  • 3.1、首先编写我们的 WebApi 服务托管对象,见下面代码
代码语言:javascript
复制


''' <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

  • 3.2、然后编写 WebAPI 控制器类(见下面代码)
代码语言:javascript
复制
''' <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

`

  • 3.3、最后编写窗体代码(见下面代码)
代码语言:javascript
复制

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

四、完整代码

代码语言:javascript
复制
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

五、示例代码项目下载

代码语言:javascript
复制
https://vbee.lanzoui.com/imffkplc8ja

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-05-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 办公魔盒 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云服务器
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档