在这篇POST里我们将实现一个简单的REST service,首先创建一个类库项目RESTService.Lib,你需要引用System.ServiceModel,与 System.ServiceModel.Web。接着我们定义一个URI的模板:

    public static class Routing
    {
        public const string GetClientRoute = "/Client/{id}";
    }
   
    然后我们来定义interface的契约:
    
    [ServiceContract(Name = "RESTDemoServices")]
    public interface IRESTDemoServices
    {
        [OperationContract]
        [WebGet(UriTemplate = Routing.GetClientRoute, BodyStyle = WebMessageBodyStyle.Bare)]
        string GetClientNameById(string Id);
    }

     来看实现类,传入一个数字返回另一个随机字符串,这里是为了演示目的,实际环境中可能是查询数据库。

namespace RESTService.Lib
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RestDemoServices:IRESTDemoServices
    {
        public string GetClientNameById(string Id)
        {
            Random r = new Random();
            string ReturnString="";
            for (int i = 0; i < Convert.ToUInt32(Id); i++)
                ReturnString += char.ConvertFromUtf32(r.Next(65, 85));
 
            return ReturnString;
 
        }
    }
}

     关于ServiceBehavior你可以参考MSDN。接下来我们可以HOST这个服务了。首先来创建一个控制台项目,代码如下:

    class Program
    {
        static void Main(string[] args)
        {
            RestDemoServices DemoServices = new RestDemoServices();
            WebHttpBinding binding = new WebHttpBinding();
            WebHttpBehavior behavior = new WebHttpBehavior();
 
            WebServiceHost _serviceHost = new WebServiceHost(DemoServices, new Uri("http://localhost:8000/DEMOService"));
            _serviceHost.AddServiceEndpoint(typeof(IRESTDemoServices), binding, "");
            _serviceHost.Open();
            Console.ReadKey();
            _serviceHost.Close();
        }
    }

    WebServiceHost类可参考MSDN

    运行后,你就可以访问这个URL http://localhost:8000/DEMOService/Clinet/22 在浏览器试试,注意,

{id} 元素匹配是interface某个方法参数的值。结果如下图:


image 

    如上图我们调用成功。当然你也可以HOST它在IIS中。创建一个Web Application 项目,创建一个.svc的项目,接入:

<%@ ServiceHost Language="C#" Debug="true" Service="RESTService.Lib.RestDemoServices" 
Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>

    然后点击右键浏览,你可以看到与上面相同的结果。可以部署.svc文件到Web服务器。

    希望这篇文章对您开发有帮助。


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on 2011-02-06 21:36  PetterLiu  阅读(15993)  评论(12编辑  收藏  举报