我稍微修改了您的WCF服务,以提供更好的示例,并编写了一个样本测试程序(请参见下文)。
第一个测试为URL http://localhost:57211/Service1.svc/getcar/1 执行GET请求。末尾的1是一个参数。端口号在您的情况下可能不同。结果如下:
{"ID":1,"Make":"Porsche"}
第二个测试执行了一个POST请求,将相同的数据(除了Ferrari改为Porsche)发送到URL http://localhost:57211/Service1.svc/updatecar/1。结果是:
{"ID":1,"Make":"Ferrari"}
这个请求同时在URL中带有参数(1),并且请求数据作为第二个参数以JSON结构的形式在请求正文中传输。
通过网络调试器查看,它会像这样(简化):
POST /Service1.svc/updatecar/1 HTTP/1.1
Host: localhost:57211
Content-Type: application/json
Content-Length: 25
{"ID":1,"Make":"Ferrari"}
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Sat, 25 Dec 2010 19:16:19 GMT
Content-Length: 25
Content-Type: application/json; charset=utf-8
{"ID":1,"Make":"Ferrari"}
希望对您有所帮助。
TestService.cs:
class TestService
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:57211/Service1.svc/getcar/1");
WebResponse response = request.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(result);
string requestData = "{\"ID\":1,\"Make\":\"Ferrari\"}";
byte[] data = Encoding.UTF8.GetBytes(requestData);
request = (HttpWebRequest)WebRequest.Create("http://localhost:57211/Service1.svc/updatecar/1");
request.Method = "POST";
request.ContentType = "application/json";
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
response = request.GetResponse();
result = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(result);
}
}
IService.cs:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/getcar/{id}")]
Car GetCar(string id);
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/updatecar/{id}")]
Car UpdateCar(string id, Car car);
}
[DataContract]
public class Car
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Make { get; set; }
}
Service.svc:
public class Service1 : IService1
{
public Car GetCar(string id)
{
return new Car { ID = int.Parse(id), Make = "Porsche" };
}
public Car UpdateCar(string f, Car car)
{
return car;
}
}
Service1.svc (Markup):
<%@ ServiceHost Language="C#" Debug="true" Service="JSONService.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>