C#实现一个简单的REST service

 在这篇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服务器。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值