Fork me on GitHub

.NET RESTful Web Services入门

  很早之前看到过RESTful Web Services,并未在意,也没找相关资料进行学习。今天偶尔有一机会,就找了点资料进行研究,发现RESTful真是“简约而不简单”。下面用示例来说明:

1 项目结构

2 REST 服务接口定义

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.ServiceModel;
 6 using System.ServiceModel.Web;
 7 namespace Jack_Restful_Service
 8 {
 9 
10     [ServiceContract(Name = "RestfulService",Namespace="http://www.cnblogs.com/isaboy")]
11     public interface IRestDemoServices
12     {
13         [OperationContract]
14         [WebGet(UriTemplate = Routing.GetClientRoute, BodyStyle = WebMessageBodyStyle.Bare)]
15         string GetClientNameById(string Id);
16 
17         [OperationContract]
18         [WebGet(UriTemplate = Routing.AddClientRoute, BodyStyle = WebMessageBodyStyle.Bare)]
19         string Add(string a, string b);
20         //error
21         //string Add(int a, int b);
22 
23         [OperationContract]
24         [WebGet(UriTemplate = Routing.LoginClientRoute, BodyStyle = WebMessageBodyStyle.Bare)]
25         string Login(string uname, string upwd);
26 
27         //post 
28         [OperationContract]
29         [WebInvoke(RequestFormat = WebMessageFormat.Json,
30         ResponseFormat = WebMessageFormat.Json,
31         BodyStyle = WebMessageBodyStyle.Bare,
32         Method = "POST", UriTemplate = "/Client/UpdateUser/{uname}")]
33         User UpdateUser(string uname, User newUser);
34 
35     }
36     //URI路由
37     public static class Routing
38     {
39         public const string GetClientRoute = "/Client/{id}";
40 
41         public const string AddClientRoute = "/Client/{a},{b}";
42         //{uname}里面的参数名称要和string Login(string uname, string upwd);一致
43         public const string LoginClientRoute = "/Client/{uname}__{upwd}";
44     }
45 
46 
47 }

 

3 REST服务接口实现

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.ServiceModel;
 6 using System.ServiceModel.Activation;
 7 namespace Jack_Restful_Service
 8 {
 9 
10     [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
11         ConcurrencyMode = ConcurrencyMode.Single,
12         IncludeExceptionDetailInFaults = true,
13         Namespace = "http://www.cnblogs.com/isaboy")]
14     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
15     public class RestDemoServices : IRestDemoServices
16     {
17         //GET
18         public string GetClientNameById(string Id)
19         {
20             string ReturnString = "Your id is: " + Id;
21 
22             return ReturnString;
23         }
24 
25         public string Add(string a, string b)
26         {
27             int sum = int.Parse(a) + int.Parse(b);
28             return sum.ToString();
29         }
30 
31         public string Login(string uname, string upwd)
32         {
33             if (uname == "admin" && upwd == "admin")
34             {
35                 return "success";
36             }
37             else
38             {
39                 return "false";
40             }
41         }
42         //POST
43         public User UpdateUser(string uname, User newUser)
44         {
45             return newUser;
46         }
47     }
48 
49 }

 

4 将服务HOST

1  Console.WriteLine("----------Restful Service Start--------------");
2  RestDemoServices demoServices = new RestDemoServices();
3  WebServiceHost _serviceHost = new WebServiceHost(demoServices, new Uri("http://localhost:8000/RestfulService"));
4   _serviceHost.Open();
5   Console.WriteLine("----------Restful Service Opened--------------");
6   Console.WriteLine("http://localhost:8000/RestfulService/Client/8");
7   Console.WriteLine("http://localhost:8000/RestfulService/Client/2,5");
8   Console.WriteLine("http://localhost:8000/RestfulService/Client/admin__admin");

5 打开浏览器,即可进行资源访问

另外,我们可以用代码进行测试

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Web;
 6 using System.Net;
 7 using System.IO;
 8 namespace PostServiceTest
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             //get
15             HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8000/RestfulService/Client/8");
16             WebResponse response = request.GetResponse();
17             string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
18             Console.WriteLine(result);
19 
20             //post
21             string requestData = "{\"uname\":\"admin\",\"upwd\":\"admin\"}";
22             byte[] data = Encoding.UTF8.GetBytes(requestData);
23             request = (HttpWebRequest)WebRequest.Create("http://localhost:8000/RestfulService/Client/UpdateUser/admin");
24             request.Method = "POST";
25             request.ContentType = "application/json";
26             Stream dataStream = request.GetRequestStream();
27             dataStream.Write(data, 0, data.Length);
28             dataStream.Close();
29 
30             response = request.GetResponse();
31             result = new StreamReader(response.GetResponseStream()).ReadToEnd();
32             Console.WriteLine(result);
33             Console.ReadKey();
34         }
35     }
36 }

 

posted @ 2016-07-01 16:56  JackWang-CUMT  阅读(3398)  评论(4编辑  收藏  举报