Fork me on GitHub

WCF构建 REST Service

今天在下试了下WCF 4新特性REST,总体比较简单。使用Online Templates中的WCF REST Service Template

imageimage

默认会有一个sampleItem的例子,和以前的WCF Service不同,这里的Service既不是一个.svc文件,也没有专门定义一个接口作为ServiceContract (服务契约)。
WCF为服务的方法不再需要标记为[OperationContract],代以[WebGet]或者[WebInvoke]来标记.
SampleItem就是以往所知的DataContract(数据契约),不过现在即使不加DataContract特性来标记也可以 。
Global.asax和Global.asax.cs。Global.asax.cs中定义了Routes,表示所有访问HOST/Service1的请求都要由Service1这个类来处理,相应UserService也是。

 

public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes();
        }

        private void RegisterRoutes()
        {
            // Edit the base address of Service1 by replacing the "Service1" string below
            RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));
            RouteTable.Routes.Add(new ServiceRoute("UserService", new WebServiceHostFactory(), typeof(UserService)));
        }
    }

UserService Code:

[ServiceContract(Namespace = "RestUserService")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class UserService
    {
        List<User> _list = GetUserData();
        private static List<User> GetUserData()
        {
            return new List<User>  
            {  
                new User { UserName="Task1", Age=100, Birthday=DateTime.Now },  
                new User { UserName="Task2", Age=100, Birthday=DateTime.Now },  
                new User { UserName="Task3", Age=100, Birthday=DateTime.Now },         
                new User { UserName="Task4", Age=100, Birthday=DateTime.Now },          
                new User { UserName="Task5", Age=100, Birthday=DateTime.Now },         
                new User { UserName="Task6", Age=100, Birthday=DateTime.Now },          
                new User { UserName="Task7", Age=100, Birthday=DateTime.Now },          
                new User { UserName="Task8", Age=100, Birthday=DateTime.Now }
            };
        }
        public void DoWork()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 默认查询
        /// </summary>
        /// <returns></returns>
        [WebGet(UriTemplate = "")]
        public List<User> GetCollection()
        {
            return _list;
        }
        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <returns></returns>
        [WebGet(UriTemplate = "/User/Xml", ResponseFormat = WebMessageFormat.Xml)]
        public List<User> GetUserXml()
        {
            return _list;
        }
        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <returns></returns>
        [WebGet(UriTemplate = "/User/Json", ResponseFormat = WebMessageFormat.Json)]
        public List<User> GetUserJson()
        {
            return _list;
        }
        /// <summary>
        /// 查询单个用户信息
        /// </summary>
        /// <returns></returns>
        [WebInvoke(UriTemplate = "/User/{Name}", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        public User GetUserByName(string name)
        {
            return GetUserData().Where(u => u.UserName == name).FirstOrDefault();
        }
        /// <summary>
        /// 添加一个用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [WebInvoke(UriTemplate = "", Method = "POST")]
        public bool Add(User user)
        {
            if (user != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 删除一个用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
        public bool Delete(string id)
        {
            return true;
        }
    }

模板默认配置了Help页面浏览即可

image

Refer:
http://debugmode.net/2011/05/15/wcf-rest-service-with-josn-data/

posted @ 2013-05-19 17:45  花儿笑弯了腰  阅读(346)  评论(0编辑  收藏  举报