WCFRest应用简介

前端之家收集整理的这篇文章主要介绍了WCFRest应用简介前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
上周末把WCFRest稍微整理了下,不料到最后一步发现Post跨域提交不成功,调查了两晚还是没有什么解决方案,暂且当作其的一个缺陷吧(本质与WCFRest无关,是JsonP不支持跨域Post,或者说JsonP跨域的本质是还是Get)。示例主要分为两个方面:1.采用模板实现WCFRest;2.采用一般WCF服务的方式实现WCFRest以及客户端的调用

1.采用模板实现WCFRest

一张图说明步骤


如图所示,建立项目,直接运行,在运行的路径后加Service1你就可以得到如下结果:


这就是WCFRest的最简单的例子,我的例子的服务代码如下:

  1. [ServiceContract]
  2. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  3. [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
  4. // NOTE: If the service is renamed,remember to update the global.asax.cs file
  5. public class LoginService
  6. {
  7. // TODO: Implement the collection resource that will contain the SampleItem instances
  8. [WebGet(UriTemplate = "All",ResponseFormat = WebMessageFormat.Json)]
  9. public List<BaseInfo> All()
  10. {
  11. List<BaseInfo> list = Factory.GetFactoryInstance(DataProviderEnum.StaticData).All();
  12. return list;
  13. }
  14. [WebGet(UriTemplate = "Login/{GID}/{PWD}",ResponseFormat = WebMessageFormat.Json)]
  15. public BaseInfo Login(string GID,string PWD)
  16. {
  17. // TODO: Replace the current implementation to return a collection of SampleItem instances
  18. return Factory.GetFactoryInstance(DataProviderEnum.StaticData).Login(GID,PWD);
  19. }
  20.  
  21. [WebInvoke(UriTemplate = "RegistLogin",Method = "POST",ResponseFormat = WebMessageFormat.Json)]
  22. public BaseInfo RegistLogin(BaseInfo baseInfo)
  23. {
  24. // TODO: Add the new instance of SampleItem to the collection
  25. return Factory.GetFactoryInstance(DataProviderEnum.StaticData).RegistLogin(baseInfo);
  26. }
  27. }
服务上面标签暂不考虑,主要关注方法上特性标签。WebGet指明方法采用Get方式,WebInvoke指示服务操作在逻辑上就是调用操作,此时需额外指定Method属性。UriTemplate服务操作的统一资源标识符 (URI) 模板,例如"Login/{Arg1}/{Arg2}",在实际运行时大括号中将以实际值填充URL;ResponseFormat返回的数据格式,有XML和Json两种,默认是XML,例子中均采用Json。
页面调用WCFRest也很简单,可通过jQuery+Ajax实现调用,示例代码如下:
  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head id="Head1" runat="server">
  3. <title></title>
  4. <script src="jquery-1.4.1.js" type="text/javascript"></script>
  5. <script type="text/javascript">
  6. function ShowAllUserInfo() {
  7.  
  8. $.ajax({
  9. type: "GET",url: "LoginService/All",contentType: "application/json;charset=utf-8",dataType: "json",cache: false,success: function (data) {
  10. $("#tabAllUser tr:gt(0)").remove();
  11. $.each(data,function (i) {
  12. $("#tabAllUser").append("<tr><td>" + data[i].GID
  13. + "</td><td>" + data[i].Name
  14. + "</td><td>" + data[i].City + "</td></tr>")
  15. })
  16. }
  17. });
  18.  
  19. }
  20. </script>
  21. </head>
  22. <body>
  23. <input id="btnGetAllInfo" type="button" onclick="ShowAllUserInfo();" value="获得所有信息" />
  24. <table id="tabAllUser">
  25. <tr>
  26. <th>
  27. GID
  28. </th>
  29. <th>
  30. Name
  31. </th>
  32. <th>
  33. City
  34. </th>
  35. </tr>
  36. </table>
  37. </body>
  38. </html>
运行效果为:

2.采用一般WCF服务的方式实现WCFRest以及客户端的调用

2.1采用一般WCF服务的方式实现WCFRest

跟一般WCF的结构一样,四个部分:契约、服务、宿主、配置文件

2.11契约:

  1. [ServiceContract]
  2. public interface ILoginService
  3. {
  4. [OperationContract(Name = "All")]
  5. [WebInvoke(Method = "GET",RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Bare,UriTemplate = "All")]
  6. List<BaseInfo> All();
  7.  
  8. [OperationContract(Name = "Login")]
  9. [WebInvoke(Method = "GET",UriTemplate = "Login/{GID}/{PWD}")]
  10. BaseInfo Login(string GID,string PWD);
  11.  
  12. [OperationContract(Name = "RegistLogin")]
  13. [WebInvoke(Method = "POST",UriTemplate = "RegistLogin")]
  14. BaseInfo RegistLogin(BaseInfo baseInfo);
  15.  
  16. [OperationContract(Name = "Regist")]
  17. [WebInvoke(Method = "POST",UriTemplate = "Regist")]
  18. void Regist(BaseInfo baseInfo);
  19. }

2.12服务:

  1. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  2. [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
  3. public class LoginService : ILoginService
  4. {
  5. public List<BaseInfo> All()
  6. {
  7. List<BaseInfo> list = Factory.GetFactoryInstance(DataProviderEnum.XML).All();
  8. return list;
  9. }
  10.  
  11. public BaseInfo Login(string GID,string PWD)
  12. {
  13. return Factory.GetFactoryInstance(DataProviderEnum.XML).Login(GID,PWD);
  14. }
  15.  
  16. public BaseInfo RegistLogin(BaseInfo baseInfo)
  17. {
  18. return Factory.GetFactoryInstance(DataProviderEnum.XML).RegistLogin(baseInfo);
  19. }
  20.  
  21.  
  22. public void Regist(BaseInfo baseInfo)
  23. {
  24. Factory.GetFactoryInstance(DataProviderEnum.XML).RegistLogin(baseInfo);
  25. }
  26. }

2.13宿主:

  1. using (WebServiceHost host = new WebServiceHost(typeof(LoginService)))
  2. {
  3. Console.WriteLine("服务正在开启...");
  4. host.Open();
  5. Console.WriteLine("服务已经开启...");
  6. Console.ReadLine();
  7. }

2.14配置文件

  1. <?xml version="1.0"?>
  2. <configuration>
  3. <system.serviceModel>
  4. <standardEndpoints>
  5. <webHttpEndpoint>
  6. <!--支持跨域,可省略(省略之后无法在浏览器中查看)-->
  7. <standardEndpoint crossDomainScriptAccessEnabled="true"/>
  8. </webHttpEndpoint>
  9. </standardEndpoints>
  10. <bindings>
  11. <webHttpBinding>
  12. <!--支持跨域,必不可少-->
  13. <binding crossDomainScriptAccessEnabled="true" />
  14. </webHttpBinding>
  15. </bindings>
  16. <services>
  17. <service name="RestService.LoginService"
  18. behaviorConfiguration="behaviorLoginService">
  19. <endpoint
  20. address="http://127.0.0.1:3741/LoginService"
  21. binding="webHttpBinding"
  22. contract="RestContract.ILoginService"/>
  23. </service>
  24. </services>
  25. <behaviors>
  26. <serviceBehaviors>
  27. <behavior name="behaviorLoginService">
  28. <serviceMetadata httpGetEnabled="True"/>
  29. </behavior>
  30. </serviceBehaviors>
  31. </behaviors>
  32. </system.serviceModel>
  33. </configuration>
注意:配置文件中两个地方需要设置crossDomainScriptAccessEnabled属性为true;在浏览器中输入http://127.0.0.1:3741/LoginService/All即提醒新建下载任务,里面就是获取的服务端的数据,可打开查看。

2.2在Asp.Net中通过JsonP访问

页面代码如下( 注意跟上面对比,dataType为JsonP):
  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head id="Head1" runat="server">
  3. <title></title>
  4. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  5. <script type="text/javascript">
  6. function ShowAllUserInfo() {
  7. $.ajax({
  8. type: "GET",url: "http://127.0.0.1:3741/LoginService/All",dataType: "jsonp",function (i) {
  9. $("#tabAllUser").append("<tr><td>" + data[i].GID
  10. + "</td><td>" + data[i].Name
  11. + "</td><td>" + data[i].City + "</td></tr>")
  12. })
  13. }
  14. });
  15.  
  16. }
  17. </script>
  18. </head>
  19. <body>
  20. <input id="btnGetAllInfo" type="button" onclick="ShowAllUserInfo();" value="获得所有信息" />
  21. <table id="tabAllUser">
  22. <tr>
  23. <th>
  24. GID
  25. </th>
  26. <th>
  27. Name
  28. </th>
  29. <th>
  30. City
  31. </th>
  32. </tr>
  33. </table>
  34. </body>
  35. </html>
先运行WCFRest服务宿主,再运行网站结果如下:

这边跟采用模板实现WCFRest的区别,模板实现的Rest无法实现跨域,这边可以跨域。

2.3一般程序中访问Rest(ConSole、Winform、WPF、服务端后台等)

主要介绍Post和Get,都是通过WebClient实现。
Get代码如下:
  1. private static string GetData(string url)
  2. {
  3. string json = string.Empty;
  4. WebClient webClient = new WebClient();
  5. Uri uri = new Uri(url,UriKind.Absolute);
  6. if (bool.Equals(false,webClient.IsBusy))
  7. {
  8. webClient.Encoding = System.Text.Encoding.UTF8;
  9. json = webClient.DownloadString(uri);
  10. }
  11. return json;
  12. }
Post代码如下:
  1. private static string PostData(string url,string jsonData)
  2. {
  3. WebClient webClient = new WebClient();
  4. byte[] byteData = Encoding.UTF8.GetBytes(jsonData.ToString());
  5. webClient.Headers.Add("Content-Type","application/json");
  6. webClient.Headers.Add("ContentLength",byteData.Length.ToString());
  7. byte[] resultData = webClient.UploadData(url,"POST",byteData);
  8. string json = Encoding.UTF8.GetString(resultData);
  9. return json;
  10. }
注意的是,这边获得的结果均为Json字符串,需要将其转换为需要的对象或者值,我这边用的第三方的Json.net实现的(个人不喜欢微软自带的序列化类,时间老有问题)。
控制台完整代码
  1. class Program
  2. {
  3. const string postRegistLoginUrl = @"http://127.0.0.1:3741/LoginService/RegistLogin";
  4. const string getAllUrl = @"http://127.0.0.1:3741/LoginService/All";
  5.  
  6. static void Main(string[] args)
  7. {
  8. Console.WriteLine("Begin");
  9.  
  10. //Post操作,RegistLogin
  11. BaseInfo newUser = new BaseInfo() { GID = "test0914",PWD = "pwd0914",Name = "name0914"};
  12. string jsonPostData = JsonConvert.SerializeObject(newUser);
  13. string postResult=PostData(postRegistLoginUrl,jsonPostData);
  14. Console.WriteLine("postRegistLogin Result:" + postResult);
  15. //Get操作,All
  16. string getResult = GetData(getAllUrl);
  17. Console.WriteLine("getAll Result:" + getResult);
  18. //返回值处理
  19. var allUserList = JsonConvert.DeserializeObject<List<BaseInfo>>(getResult);
  20. foreach (var user in allUserList)
  21. {
  22. string userInfo = string.Format("GID:{0};Name:{1};City:{2}",user.GID,user.Name,user.City);
  23. Console.WriteLine(userInfo);
  24. }
  25.  
  26. Console.WriteLine("End");
  27. Console.ReadLine();
  28. }
  29.  
  30. private static string GetData(string url)
  31. {
  32. string json = string.Empty;
  33. WebClient webClient = new WebClient();
  34. Uri uri = new Uri(url,UriKind.Absolute);
  35. if (bool.Equals(false,webClient.IsBusy))
  36. {
  37. webClient.Encoding = System.Text.Encoding.UTF8;
  38. json = webClient.DownloadString(uri);
  39. }
  40. return json;
  41. }
  42.  
  43. private static string PostData(string url,string jsonData)
  44. {
  45. WebClient webClient = new WebClient();
  46. byte[] byteData = Encoding.UTF8.GetBytes(jsonData.ToString());
  47. webClient.Headers.Add("Content-Type","application/json");
  48. webClient.Headers.Add("ContentLength",byteData.Length.ToString());
  49. byte[] resultData = webClient.UploadData(url,byteData);
  50. string json = Encoding.UTF8.GetString(resultData);
  51. return json;
  52. }
  53. }
项目整体结构如下:

2.4Android访问WCFRest(参照上篇博客

3.小结

个人觉得在内部网站项目中可以采用模板实现WCFRest,优点是安全和解耦,缺点是无法跨域访问、发布只能通过IIS发布。对于多平台的接口(Android、桌面和服务端,不包含复杂的Web应用)可以考虑采用WCFRest。如果也包括Web应用可以考虑采用其他绑定的WCF,一般也不考虑Webservice了。

至此全部完成,只是个人的一些实践,对自己是一个记录,同时希望也能对别人有些帮助,如果有什么错误,还望不吝指出,共同进步,转载请保留原文地址

源码下载

猜你在找的Json相关文章