前言
编写的客户端需要启动WEB服务,接受其他项目的回调
项目使用的框架版本:.NET Framework 4.7.2
步骤
一、引入依赖
- Microsoft.AspNet.WebApi.Client
- Microsoft.AspNet.WebApi.SelfHost
二、编写HttpServer.cs
,作为HTTP服务的启动类
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace StudyToolbox
{
public class HttpServer
{
private HttpSelfHostServer server;
public HttpServer(string ip, int port)
{
var config = new HttpSelfHostConfiguration($"http://{ip}:{port}"); //创建宿主服务
config.MapHttpAttributeRoutes(); //添加路由属性
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}"); //指定路由规则
// 默认首页路由
config.Routes.MapHttpRoute(name: "Root", routeTemplate: "",
defaults: new { controller = "Home", action = "Index" });
server = new HttpSelfHostServer(config);
}
/// <summary>
/// 开启服务(异步任务方式)
/// </summary>
/// <returns></returns>
public Task StartHttpServer()
{
return server.OpenAsync();
}
/// <summary>
/// 关闭服务(异步任务方式)
/// </summary>
/// <returns></returns>
public Task CloseHttpServer()
{
return server.CloseAsync();
}
}
}
三、编写控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace StudyToolbox.Web.Controller
{
public class HomeController:ApiController
{
[HttpGet]
public IHttpActionResult Index()
{
return Json("成功接入StudyToolbox的服务端页面");
}
[HttpGet]
public IHttpActionResult HelloWork()
{
return Json("xxx");
}
}
}
四、访问
引用
1.Winform窗体利用WebApi接口实现ModbusTCP数据服务:https://blog.csdn.net/hqwest/article/details/130797598
评论 (0)