WebApi 自宿主一例,关于Web Api的基础入门和相关概念可以参考
1. 简介
WebAPI 托管有两种方式一种是通过IIS,一种就是通过寄宿在其他程序,例如window服务,window应用程序等等,前者主要用于发布和最后调试使用,后者一般多在开发测试环节。
我们知道WCF服务可以通过System.ServiceModel.ServiceHost来加载和打开服务,那么web api可以通过System.Web.Http.SelfHost.HttpSelfHostServer来加载打开API服务
在使用System.Web.Http.SelfHost.HttpSelfHostServer来打开服务的时候,需要通过HttpSelfHostConfiguration来配置下主机一些参数(主要是服务地址)
2.实例
1) 通过VS2012新建一个window form工程,然后通过Nuget获取WebAPI SeltHost库,下载安装后的包:
引用命名空间:
using System.Web.Http; using System.Web.Http.SelfHost;
声明变量:主机服务和配置实例对象
private HttpSelfHostConfiguration _config = null; private HttpSelfHostServer _serverhost = null;
初始化:
_config = new HttpSelfHostConfiguration("http://localhost:5555");
API路由 +打开服务
_config.Routes.MapHttpRoute( "API Default", "api/{controller}/{username}", new { username = RouteParameter.Optional }); //start _serverhost = new HttpSelfHostServer(_config); _serverhost.OpenAsync().Wait();
模型类:
public class UserModel { [Required] [StringLength(16,MinimumLength=4)] public string UserName { get; set; } [Required] [StringLength(16,MinimumLength=4)] public string Password { get; set; } [Required] [RegularExpression(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")] public string Email { get; set; } [Required] [Range(18,36)] public int Age { get; set; } }
接下来我们需要设计一个测试客户端来验证我们的API
2) 新建一个window form工程,依旧是通过NuGet获取WebAPI Client库(用于桌面客户端程序请求API服务)
声明一个HttpClient对象,并初始化API服务地址
private HttpClient _httpCLient = new HttpClient(); _httpCLient.BaseAddress =new Uri( @"http://localhost:5555");
调用
private void GetUsers() { HttpResponseMessage responseMsg = _httpCLient.GetAsync("api/user").Result; responseMsg.EnsureSuccessStatusCode(); var users = responseMsg.Content.ReadAsAsync<IEnumerable<UserModel>>().Result; string msg = string.Empty; foreach (var o in users) { msg += string.Format("Name:{0} , Email:{1} , Age:{2}", o.UserName, o.Email, o.Age); msg += System.Environment.NewLine; } MessageBox.Show(msg); }
程序运行效果图:
点击initConfig(配置/打开服务) ---- 》 点击Get( 测api/User,获取所有用户信息)