在Windows平台web服务一般托管于ISS。在开发中,会遇到需要上位机工程师提供对外API服务,本文将用WPF代码实现。
先看效果图
软件界面:
服务界面
需要引入开发包
|
|
|
Newtonsoft.Json |
下图为代码简单框架
HttpService.cs:HTTP 服务类
HomeController.cs:控制器,用于相应WebApi响应
1.搭建WPF主界面
MainWindow.xaml
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Port:" Margin="10"/>
<TextBox x:Name="TextBox_Port" Text="8080" Width="100" Margin="10"/>
<Button x:Name="Btn_Start" Content="开始" Width="50" Margin="10" Click="Btn_Start_Click"/>
<Button x:Name="Btn_Stop" Content="结束" Width="50" Margin="10" Click="Btn_Stop_Click"/>
</StackPanel>
</StackPanel>
</Grid>
2.MainWindow.xaml.cs
private HttpService _http;//服务对象
///打开
private async void Btn_Start_Click(object sender, RoutedEventArgs e)
{
try
{
var port = Convert.ToInt32(TextBox_Port.Text);
_http = new HttpService(port);
await _http.StartHttpServer();
}
catch(Exception ex)
{
LogHelper.WriteLogByType(LogEnum.Error, ex.Message);
}
}
//关闭
private async void Btn_Stop_Click(object sender, RoutedEventArgs e)
{
try
{
await _http.CloseHttpServer();
_http.Dispose();
}
catch (Exception ex)
{
LogHelper.WriteLogByType(LogEnum.Error, ex.Message);
}
}
3.HTTP服务类代码文章来源:https://www.toymoban.com/news/detail-609216.html
public class HttpService : IDisposable
{
/// <summary>
/// 端口号
/// </summary>
public int Port { get;set; }
/// <summary>
/// Http self hosting
/// </summary>
private readonly HttpSelfHostServer _server;
public HttpService(int port)
{
this.Port = port;
var config = new HttpSelfHostConfiguration($"http://localHost:{this.Port}");
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");
_server = new HttpSelfHostServer(config);
}
#region HTTP Service
/// <summary>
/// start HTTP server
/// </summary>
/// <returns></returns>
public Task StartHttpServer()
{
return _server.OpenAsync();
}
/// <summary>
/// Close HTTP service
/// </summary>
/// <returns></returns>
public Task CloseHttpServer()
{
return _server.CloseAsync();
}
#endregion
public void Dispose()
{
_server.Dispose();
}
}
4.控制器代码文章来源地址https://www.toymoban.com/news/detail-609216.html
[RoutePrefix("api/home")]
public class HomeController:ApiController
{
[Route("echo")]
[HttpGet]
public IHttpActionResult Echo(string name)
{
return Json(new { Name = name, Message = $"Hello,{name},action"});
}
}
到了这里,关于关于如何用WPF实现WebApi自托管服务及交互的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!