记录一下使用Fiddler进行模拟请求的经过。^-^
首先利用WCF+REST搭建一个支持REST的wcf服务,添加几个测试用的服务接口。
服务代码如下:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
// NOTE: If the service is renamed, remember to update the global.asax.cs file
public class Service1
{
// TODO: Implement the collection resource that will contain the SampleItem instances
[WebGet(UriTemplate = "")]
public List<SampleItem> GetCollection()
{
// TODO: Replace the current implementation to return a collection of SampleItem instances
return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
}
[WebInvoke(UriTemplate = "", Method = "POST")]
public SampleItem Create(SampleItem instance)
{
// TODO: Add the new instance of SampleItem to the collection
//throw new NotImplementedException();
//
return new SampleItem() { StringValue = "字符串内容", Id = 2147483647 };
}
[WebGet(UriTemplate = "{id}")]
public SampleItem Get(string id)
{
// TODO: Return the instance of SampleItem with the given id
throw new NotImplementedException();
}
[WebInvoke(UriTemplate = "{id}", Method = "PUT")]
public SampleItem Update(string id, SampleItem instance)
{
// TODO: Update the given instance of SampleItem in the collection
throw new NotImplementedException();
}
[WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
public void Delete(string id)
{
// TODO: Remove the instance of SampleItem with the given id from the collection
throw new NotImplementedException();
}
}
需要添加路由,该服务才能生效。在Global文件中添加跳转到该服务的路由。
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));
}
}
服务创建完成后,在浏览器中可以查看服务说明了。
- 一、Get
利用Fiddler测试Get
服务地址为http://localhost/WcfRestService1/Service1
点击Excute,请求结果如下:
- 二、POST
1、json格式
请求地址为http://localhost/WcfRestService1/Service1
请求POST的Headers为
Body为Content-Length: 57 Host: localhost Content-Type: application/json; charset=utf-8
如图:{ "Id":2147483647, "StringValue":"字符串内容" }
请求结果如下:
2、xml格式
请求地址为http://localhost/WcfRestService1/Service1
请求POST的Headers为
Content-Length: 160 Host: localhost Content-Type: text/html; charset=utf-8
Body为:
如图:<SampleItem xmlns="http://schemas.datacontract.org/2004/07/WcfRestService1"> <Id>2147483647</Id> <StringValue>字符串内容</StringValue> </SampleItem>
请求结果如图: