java 单机接口限流处理方案
460
2022-06-07
在 Windows 平台 Web 服务一般托管于 IIS. 在开发中, 会遇到 WinForms 或 WPF 服务端程序需要提供对外 API 作为服务. 在本文详细介绍 WebApi 自托管于 WinForms 中, WPF 或 Console 程序实现类似.
如下图所示:
绘制必要控件, 布局如下:
备注: 绘制一个 NumericUpDown 和两个 Button 控件.
/// <summary>
/// HTTP service.
/// </summary>
public class HttpService
{
/// <summary>
/// HTTP self hosting.
/// </summary>
private HttpSelfHostServer _server;
#region HTTP Service
/// <summary>
/// start HTTP server.
/// </summary>
/// <param name="port">the port of the http server</param>
public void StartHttpServer(string port)
{
var config = new HttpSelfHostConfiguration($"http://0.0.0.0:{port}");
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");
this._server = new HttpSelfHostServer(config);
this._server.OpenAsync().Wait();
}
/// <summary>
/// Close HTTP server.
/// </summary>
public void CloseHttpServer()
{
this._server.CloseAsync().Wait();
this._server.Dispose();
}
#endregion
}
WebApi 自托管服务主要由 HttpSelfHostServer
实现.
config.MapHttpAttributeRoutes();
可以在 Controller
中使用路由特性.
在 MainForm 窗体程序中引用 HTTP 服务:
public class MainForm:Form
{
/// <summary>
/// Http service.
/// </summary>
private readonly HttpService _http;
public MainForm()
{
/**
* initialize http service.
*/
_http = new HttpService();
}
}
/// <summary>
/// start the http server.
/// </summary>
private void StartButton_Click(object sender, EventArgs e)
{
/**
* start.
*/
try
{
var port = this.PortNum.Value;
_http.StartHttpServer($"{port}");
}
catch (Exception exception)
{
MessageBox.Show($"{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// close the http server.
/// </summary>
private void CloseButton_Click(object sender, EventArgs e)
{
/**
* close.
*/
try
{
_http.CloseHttpServer();
}
catch (Exception exception)
{
MessageBox.Show($"{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Home controller.
/// </summary>
[RoutePrefix("api/home")]
public class HomeController : ApiController
{
/// <summary>
/// Print the greetings
/// </summary>
/// <param name="name">visitor</param>
/// <returns>greetings</returns>
[Route("echo")]
[HttpGet]
public IHttpActionResult Echo(string name)
{
return Json(new {Name = name, Message = $"Hello, {name}"});
}
}
下载完整示例代码 (GitHub)
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~