本教程只针对.net framework 4.0
新建窗体项目名为Demo1
在程序包管理控制器中输入:Microsoft.AspNet.WebApi.SelfHost搜索对应的nuget包
新增窗体form1。在窗体里面放置一个按钮名为button1。双击button自动生成代码段,并在代码段内输入以下内容:
using System.Web.Http; using System.Web.Http.SelfHost; private void button1_Click(object sender, EventArgs e) { HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost:8002"); configuration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); HttpSelfHostServer HttpSelfHostServer = new HttpSelfHostServer(configuration); HttpSelfHostServer.OpenAsync().Wait(); }
4.新增类TestController,代码如下
public class TestController : ApiController { public string Get() { return "Hello world"; } }
5.点击运行。弹出窗体。点击窗体上的button1按钮。然后浏览器中输入http://localhost:8002/api/Test 即显示Hello world字符串