一个windowsform程序,不依赖IIS,采用selfhost方式及Owin框架提供Web API。该windowsform程序通过按钮可以开启或关闭Web API服务。请给出C#详细例子
时间: 2023-06-27 21:01:32 浏览: 204
一个不错的C#WinForm程序示例
4星 · 用户满意度95%
首先,需要安装Microsoft.AspNet.WebApi.OwinSelfHost NuGet包。然后,在Windows Form应用程序中添加以下代码:
```csharp
using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
namespace SelfHostWebApi
{
public partial class MainForm : Form
{
private IDisposable _webApp;
public MainForm()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
_webApp = WebApp.Start<Startup>(url: baseAddress);
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/values").Result;
txtOutput.Text += response;
}
private void btnStop_Click(object sender, EventArgs e)
{
// Dispose web app
_webApp.Dispose();
}
}
}
```
接下来,需要创建Startup类,该类将配置Web API路由,如下所示:
```csharp
using Microsoft.AspNet.WebApi.OwinSelfHost;
using System.Web.Http;
namespace SelfHostWebApi
{
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
```
最后,需要创建一个Web API控制器,如下所示:
```csharp
using System.Collections.Generic;
using System.Web.Http;
namespace SelfHostWebApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
```
现在,您的Windows Form应用程序可以通过Owin框架提供Web API服务。通过单击“Start”按钮,您将启动Web API服务。通过单击“Stop”按钮,您将停止Web API服务。
阅读全文