程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> .NET RESTful Web Services入門,.netrestful

.NET RESTful Web Services入門,.netrestful

編輯:C#入門知識

.NET RESTful Web Services入門,.netrestful


  很早之前看到過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 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved