本文共 6175 字,大约阅读时间需要 20 分钟。
WebApi 相对 WebService 在数据传送格式,部署方式上更加灵活多样,目前的应用已经非常广泛.Web API常见以 Web方式部署, 下面我们看下 以 Console Application 和 Winform Application为宿主的部署.
一. 以Console application为宿主部署.
Step1: 两种方式都需要先NUGET安装或引用 webapi 和 selfhost Step2. 在Console Application 项目的 Program.cs 中注册 web api serverusing 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 apiImports 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/