今天有在研究SignalR, 发现SignalR可以使用Self-Host的方式,就突发奇想,Web Api是不是也可以使用Self-Host的方式寄宿在Console Application或者其他的地方。
微软MSDN上给出的详细的答案,Web Api和WCF以及SignalR一样,支持Self-Host。
创建Self-Host项目
新建Console Application
创建成功之后,使用Nuget引入Web Api和Owin包。
打开Package Manager Console, 在里面录入以下命令
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
配置Web API Self-Host
在解决方案管理窗口,右键点击项目,选择Add/Class, 添加一个新文件Startup.cs
在Startup.cs中添加Configuration方法,该方法中指定了当前项目启用Web Api并指定了路由规则
using Owin;
using System.Web.Http;
namespace OwinSelfhostSample
{
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 Controller
在解决方案中,右键点击项目,选择Add/Class, 添加ValuesController.cs
using System.Collections.Generic;
using System.Web.Http;
namespace OwinSelfhostSample
{
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)
{
}
}
}
使用Owin Host
修改Program.cs, 定义web api的base url, 并启动Owin Host
using Microsoft.Owin.Hosting;
using System;
namespace SelfHost
{
class Program
{
static void Main(string[] args)
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
Console.WriteLine("App Server started.");
Console.ReadLine();
}
}
}
}
使用Postman测试Api
启动解决方案,等待程序显示”App Server Started.”
打开Postman输入测试的Api Url, 即得到正确的结果。