1:新建WCF服务应用程序,名称为RestWCF,选择在新网站中承载.
2:新建实体类Product,代码如下:
public class Product
{
[DataMember]
public Guid Id { get ; set ; }
[DataMember]
public String Name { get ; set ; }
}
3:新建服务契约IProductService:
public interface IProductService
{
[OperationContract]
[WebGet(UriTemplate = " Product " )]
List < Product > GetProducts();
[OperationContract]
[WebInvoke(UriTemplate = " Product " ,Method = " PUT " )]
bool CreateProduct(Product product);
[OperationContract]
[WebInvoke(UriTemplate = " Product " , Method = " POST " )]
bool UpdateProduct(Product product);
[OperationContract]
[WebInvoke(UriTemplate = " Product " , Method = " DELETE " )]
bool DeleteProduct(Product product);
}
注意的是这里都是一些CRUD操作,但是除了OperationContract修饰外,还有WebGet,WebInvoke特性来修饰。
UriTemplate就是Uri模版的意思,如果web地址为http://www.rest.com.那么rest服务的地址就是http://www.rest.com/Product.
OK.上面的契约大致表示
GET-----GetProducts方法。
PUT-----CreateProduct.
POST----UpdateProduct
DELETE---DeleteProduct。
4:新建服务类:ProductService,实现服务接口,代码如下:
{
public List < Product > GetProducts()
{
return new List < Product > ()
{
new Product(){ Id = Guid.NewGuid(), Name = " 111 " },
new Product(){ Id = Guid.NewGuid(), Name = " 222 " },
new Product(){ Id = Guid.NewGuid(), Name = " 333 " },
};
}
public bool CreateProduct(Product product)
{
return true ;
}
public bool UpdateProduct(Product product)
{
return true ;
}
public bool DeleteProduct(Product product)
{
return true ;
}
}
当然了,实际上肯定是数据库操作,在这里我们就先Mock一下吧。
5:新建ProductService.svc文件,代码如下:
这里有一点要注意。Service对应的是包含类的全部名称=命名空间+类名.
6:配置web.config文件。
< services >
< service name = " RestWCF.ProductService " >
< endpoint address = "" behaviorConfiguration = " RestBehavior " binding = " webHttpBinding "
bindingConfiguration = "" contract = " RestWCF.IProductService " />
</ service >
</ services >
< behaviors >
< endpointBehaviors >
< behavior name = " RestBehavior " >
< webHttp helpEnabled = " true " defaultBodyStyle = " Bare " defaultOutgoingResponseFormat = " Json " />
</ behavior >
</ endpointBehaviors >
< serviceBehaviors >
< behavior name = "" >
< serviceMetadata httpGetEnabled = " true " />
< serviceDebug includeExceptionDetailInFaults = " false " />
</ behavior >
</ serviceBehaviors >
</ behaviors >
< serviceHostingEnvironment multipleSiteBindingsEnabled = " true " />
</ system.serviceModel >
在这里因为要配置Rest服务,所以我们添加webHttp Behavior,并且启用helpEnabled.在这里我们设置defaultBodyStyle="Bare"代表不包装。
defaultOutgoingResonseFormat="Json",则代表默认输出的格式是json,如果不设置的话,默认是xml。
7:在浏览器中浏览,因为我们启用了HelpEnabled.所以我们输入的地址是:
8:OK,服务我们已经配置完成了,我们还是测试下吧,打开fiddler.
结果如下:
在这里我们提交下POST请求。
下回我们将使用Silverlight来调用Get,Post,Put,Delete的Rest服务。
oh,我忘记了,这些全部是大写,所以你最好记住GET,POST,PUT,DELETE.