WebApi 是目前用做基于Http协议进行数据交换服务的最流行技术之一。Asp.net mvc4以后VS自带webapi功能,用户可以通过模板快速开发api程序,而api的部署不像web程序只能寄宿到IIS,当然可能的话你也是自己动手编写自己的web服务器,这当然是不提倡的事了,自己做无用的轮子。 通过自主宿主你可以把一个webapi宿主到一个console控制台程序上或者windowService上,在项目中编写windowService程序有时候或多或少的需要向外提供一些api接口,这个时候SelfHost就可以派得上场了,本例子使用console程序作为演示。
实现WebApiSelfHost的步骤比较简单
第一步:引用WebApi 和SelfHost所需的程序集(4个dll),也可以通过Nuget方式进行获取
第二步:编写api控制器
public class TestController : ApiController { [HttpGet] public IList<User> GetUser() { var user = new User { Id = 99, UserName = "TestUser" }; var list = new List<User>(); list.Add(user); list.Add(user); return list; } } public class User { public int Id { get; set; } public string UserName { get; set; } public DateTime CreateTime { get { return DateTime.Now; } } }
第三步:编写SelfHost服务,简简单单的几句代码即见效果
class Program { static HttpSelfHostServer server = null; static void Main(string[] args) { ResisterController(); while (true) { Console.ReadKey(); } } static void ResisterController() { string url = "http://127.0.0.1:8001"; HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(url); //提交json数据返回的支持,默认是返回xml格式数据 //本例子为了迎合jQuery的ajax 请求,添加datatype参数映射,这样ajax指定datatype:json的时候就自动返回json数据给浏览器 config.Formatters.JsonFormatter.MediaTypeMappings.Add( new QueryStringMapping("datatype", "json", "application/json")); //注册路由 config.Routes.MapHttpRoute( name: "test-api", routeTemplate: "{controller}", defaults: new { controller = "Test" } ); //打开服务 server = new HttpSelfHostServer(config); server.OpenAsync().Wait(); } }
第四步:前面已经大功告成,运行测试看看效果吧