一直以来都想找一种数据通信方式,就像是asp.net中的*ashx程序一样的应用,什么意思呢,就是不论是浏览器,android,iso,wp,一切可上网的设备都可以使用的一种数据服务,
然后ashx似的网页应用程序在一定的程度上面还是有许多的限制,今天接触到了wcf中的rest服务,使用的是vs2010 .net4.0,接下来让我们一起来体验一回神奇的服务。
一.创建应用接口
1.1IDataDal.cs内部代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace WCF.RestFul.IServices
{
[ServiceContract]
public interface IDataDal
{
//[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
List<Data> getdata();
}
//自定义数据类型
public class Data
{
public string Co2;
public string Light;
public string Wendu;
}
}
二.实现接口,定义服务,此添加的是一个控制应用程序,也是服务宿主
2.2 Program.cs代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCF.RestFul.IServices;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
namespace WCF.RestFul.Service
{
class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(DataDal));
host.Open();
Console.WriteLine("服务已经打开!!!");
Console.Read();
}
}
public class DataDal : IDataDal
{
#region IDataDal 成员
//
//[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/DataDal/getdata")]
[WebGet(UriTemplate = "/getdata", ResponseFormat = WebMessageFormat.Json)]
public List<Data> getdata()
{
Data d1 = new Data { Co2="1", Light="2", Wendu="3" };
Data d2 = new Data { Co2 = "1", Light = "2", Wendu = "3" };
Data d3 = new Data { Co2 = "1", Light = "2", Wendu = "3" };
List<Data> list = new List<Data>();
list.Add(d1);
list.Add(d2);
list.Add(d3);
return list;
}
#endregion
}
}
2.2使用倒置文件
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="WCF.RestFul.Service.DataDal" behaviorConfiguration="client1">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8001/DataDal"/>
</baseAddresses>
</host>
<!--以下的webHttpBinding绑定-->
<endpoint address="" binding="webHttpBinding" contract="WCF.RestFul.IServices.IDataDal" behaviorConfiguration="help"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="client1">
<!--此项设定可以实现用浏览器查看方法的使用介绍,较利于开发者-->
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="help">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
三。开始运行服务
3.1检测服务
3.2查看代码接口帮助页面
4在浏览器里面调用此服务