产品及架构介绍
定义
命名空间:TouchSocket.WebApi
程序集:TouchSocket.WebApi.dll
一、说明
WebApi是通用的Rpc调用,与编程语言无关,与操作系统无关。其路由机制模仿AspNetCore,可实现很多路由机制。但是因为http兼容性错综复杂,所以目前TouchSocket的WebApi仅支持GET、POST函数。使用体验接近于AspNetCore。
二、特点
- 高性能,100个客户端,10w次调用,仅用时17s。
- 全异常反馈 。
- 支持大部分路由规则。
- 支持js、Android等调用。
三、定义服务
在服务器端中新建一个类,继承于RpcServer类(或实现IRpcServer),然后在该类中写公共方法,并用WebApi属性标签标记。
public partial class ApiServer : RpcServer
{
private readonly ILog m_logger;
public ApiServer(ILog logger)
{
this.m_logger = logger;
}
[WebApi(Method = HttpMethodType.Get)]
public int Sum(int a, int b)
{
return a + b;
}
}
四、启动服务器
更多注册Rpc的方法请看注册Rpc服务
var service = new HttpService();
await service.SetupAsync(new TouchSocketConfig()
.SetListenIPHosts(7789)
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
a.AddRpcStore(store =>
{
store.RegisterServer<ApiServer>();//注册服务
});
})
.ConfigurePlugins(a =>
{
a.UseCheckClear();
a.UseWebApi();
//此插件是http的兜底插件,应该最后添加。作用是当所有路由不匹配时返回404.且内部也会处理Option请求。可以更好的处理来自浏览器的跨域探测。
a.UseDefaultHttpServicePlugin();
}));
await service.StartAsync();
Console.WriteLine("以下连接用于测试webApi");
Console.WriteLine($"使用:http://127.0.0.1:7789/ApiServer/Sum?a=10&b=20");
五、参数规则
5.1 Get规则
使用Get
进行请求时,服务方法可以声明多个参数,但是每个参数都必须是简单类型(例如:int、string、DateTime等)。
[WebApi(Method = HttpMethodType.Get)]
public int Get(int a)
{
return a;
}
[WebApi(Method = HttpMethodType.Get)]
public int Sum(int a, int b)
{
return a + b;
}