博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vs中 WebAPI 以Console application和WinForm作为宿主的部署
阅读量:4041 次
发布时间:2019-05-24

本文共 6175 字,大约阅读时间需要 20 分钟。

WebApi 相对 WebService 在数据传送格式,部署方式上更加灵活多样,目前的应用已经非常广泛.Web API常见以 Web方式部署, 下面我们看下 以 Console Application 和 Winform Application为宿主的部署.

一. 以Console application为宿主部署.

Step1: 两种方式都需要先NUGET安装或引用 webapi 和 selfhost
在这里插入图片描述
Step2.  在Console Application 项目的 Program.cs 中注册 web api server

using System.Web.Http;using System.Web;using System.Web.Http.SelfHost;static Main(string[] args){
RegisterWebApi("http://localhost:1234");} private static void RegisterWebApi(string url) {
try {
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(url);//( "http://localhost:1234"); config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new {
id = RouteParameter.Optional }); using (var sever = new HttpSelfHostServer(config)) {
sever.OpenAsync().Wait(); Console.WriteLine("Web API is running...."); Console.WriteLine("Any keypress to exit."); Console.Read(); sever.CloseAsync().Wait(); } } catch (Exception ex) {
Console.WriteLine(ex.Message); } }

Step3:  在项目中新增一个Controller类文件

using System.Web.Http;    public class LoginController : ApiController    {
//Get http://localhost:1234/api/Login/GetTest?userName=admin&pwd=123456 [HttpGet] public string GetTest(string userName, string pwd) {
if (userName == "admin" && pwd == "123456") {
return "ok"; } else {
return "error"; } } }

Step4:  执行.记得要有 管理员权限(打开vs 时选择管理员运行,或项目编译后的exe文件用管理员权限运行)

在这里插入图片描述

测试,例如使用 postman

在这里插入图片描述

二,以WinForm 为宿主部署,并与Winform 交互数据.

Step1:NUGET安装或引用 webapi 和 selfhost

Step2:在Form(本例FormName为AppForm)中注册 Wep API Server

(VB.NET )

Imports System.Web.HttpImports System.WebImports System.Web.Http.SelfHost     Public config As HttpSelfHostConfiguration = Nothing        Public server As HttpSelfHostServer = Nothing        Public Shared frmApp As AppForm   '与 controller 交互数据用                'Register web api server        Private Async Sub RegistWebApi()            Try                If (server Is Nothing) Then                    config = New HttpSelfHostConfiguration("http://localhost:1234")                    config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", New With {.id = RouteParameter.Optional})                    server = New HttpSelfHostServer(config)                                       Await server.OpenAsync()                               End If            Catch ex As Exception                Throw ex            End Try        End Sub                'Dispose web api         Private Sub DisposeWebApi()            Try                If (server IsNot Nothing) Then                    server.CloseAsync().Wait()                    server.Dispose()                    server = Nothing                    GC.Collect()                    functionCallStatusLabel.Text += " ;WebAPI Server Stop."                End If            Catch ex As Exception                Throw ex            End Try        End Sub        Public Function GetRFIDTag() As IEnumerable(Of String)            Dim rtnTag As New List(Of String)            rtnTag.Add(DateTime.Now.ToString()) '从 页面的ListView中读数据,并返回给 调用本函数的 Controller .注意这里用了 Invoke,因为客户端可能经Task等子线程调用controller再调用本函数            ListView1.Invoke(New Action(Sub()                                                For Each it As ListViewItem In ListView1.Items                                                    rtnTag.Add(it.SubItems(0).Text.Trim.ToString())      'Get TagId                                                    rtnTag.Add(HexToString(it.SubItems(0).Text.Trim.ToString()))                                                Next                                            End Sub))            Return rtnTag        End Function         Private Sub AppForm_Load(ByVal sender As Object, ByVal e As EventArgs)                      RegisterWebApi()            frmApp = Me  '与 controller 交互数据用  End Sub

Step3: 增加 Controller

Public Class RFIDController : Inherits ApiController    'Get http://localhost:1234/api/RFID/GetTagId    Public Function GetTagId() As IEnumerable(Of String)        Return AppForm.GetRFIDTag()    '.frmApp.GetRFIDTag()    End FunctionEnd Class

测试:

1. 用 postman
在这里插入图片描述
2. 其它 winform程序 后台调用上面的 web api

Imports System.Net.HttpImports Newtonsoft.JsonPublic Class frmMain    Private Async Sub btnGet_Click(sender As Object, e As EventArgs) Handles btnGet.Click        Dim Items As List(Of String) = New List(Of String)()        Dim t As Task(Of List(Of String)) = Task.Run(Function()                                                         Return DownloadPageAsync(txtURL.Text.Trim)                                                     End Function)        Items = Await t        Items.ForEach(Sub(o)                          txtValue.AppendText(o.ToString() + Environment.NewLine)                      End Sub)    End Sub       Private Async Function DownloadPageAsync(ByVal url As String) As Task(Of List(Of String))        Dim page As String = url        Dim Items As List(Of String) = New List(Of String)()        ' Use HttpClient in Using-statement.        ' ... Use GetAsync to get the page data.        Using client As HttpClient = New HttpClient()            Using response As HttpResponseMessage = Await client.GetAsync(page)                Using content As HttpContent = response.Content                    ' Get contents of page as a String.                    Dim result As String = Await content.ReadAsStringAsync()                    ' If data exists, print a substring.                    If result IsNot Nothing Then                        Items = JsonConvert.DeserializeObject(Of List(Of String))(result)                    End If                End Using            End Using        End Using        Return Items    End FunctionEnd Class

在这里插入图片描述

转载地址:http://rsmdi.baihongyu.com/

你可能感兴趣的文章
gdb debug tips
查看>>
arm linux 生成火焰图
查看>>
linux和windows内存布局验证
查看>>
linux insmod error -1 required key invalid
查看>>
linux kconfig配置
查看>>
linux不同模块completion通信
查看>>
linux printf获得时间戳
查看>>
C语言位扩展
查看>>
linux dump_backtrace
查看>>
linux irqdebug
查看>>
git 常用命令
查看>>
linux位操作API
查看>>
uboot.lds文件分析
查看>>
uboot start.s文件分析
查看>>
没有路由器的情况下,开发板,虚拟机Ubuntu,win10主机,三者也可以ping通
查看>>
本地服务方式搭建etcd集群
查看>>
安装k8s Master高可用集群
查看>>
忽略图片透明区域的事件(Flex)
查看>>
忽略图片透明区域的事件(Flex)
查看>>
AS3 Flex基础知识100条
查看>>