webapi winform
时间: 2023-10-28 15:06:52 浏览: 145
webapi寄宿于winform
3星 · 编辑精心推荐
winform中寄宿webapi的过程如下:首先,在winform项目中添加以下代码段,创建一个新的线程,并在其中加载WebApi程序集,配置HttpSelfHostConfiguration对象并创建HttpSelfHostServer对象,最后启动服务器。
```csharp
Thread td = new Thread(new ThreadStart(() =>
{
try
{
Assembly.Load("WebApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost/selfhost");
configuration.TransferMode = TransferMode.Streamed;
HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration);
httpServer.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
httpServer.OpenAsync().Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}));
td.IsBackground = true;
Console.WriteLine(td.IsBackground);
td.Start();
```
另外,确保已安装以下DLL文件:Microsoft.AspNet.WebApi.Client、Microsoft.AspNet.WebApi.SelfHost。
此外,你还可以使用自定义的HttpServer类来管理WebApi服务。下面是一个示例代码:
```csharp
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}");
server = new HttpSelfHostServer(config);
}
public Task StartHttpServer()
{
return server.OpenAsync();
}
public Task CloseHttpServer()
{
return server.CloseAsync();
}
}
```
阅读全文