通过HttpWebRequest调用wcf服务

时间:2011-09-20 22:43:24

标签: wcf post

当我有这项服务时:

[OperationContract]
ResponseMessage GetData(RequestMessage message);

其中

class RequestMessage
{
  public string data    
}

class ResponseMessage
{
  public string data
}

并调用此服务

string data2 = ""
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/Service.svc/GetData");
request.ContentType = "application/json";
request.Method = "POST";
request.KeepAlive = true;

using (Stream requestStream = request.GetRequestStream())
{
  var bytes = Encoding.UTF8.GetBytes(data2);
  requestStream.Write(bytes, 0, bytes.Length);
  requestStream.Close();
}

var response = (HttpWebResponse)request.GetResponse();
var abc = new StreamReader(response.GetResponseStream()).ReadToEnd();

作为data2我应该发送字符串“mydata”还是应该用json格式包装它:{“message”:{“data”:“mydata”}}

?? 我有理解如何通过邮件在客户端发送数据以在服务端正确地获取数据:/

1 个答案:

答案 0 :(得分:1)

您没有提及如何定义服务。假设您的端点使用webHttpBinding,并且端点行为<webHttp/>具有默认值,则正文样式的默认值为“Bare”,这意味着请求应仅包含序列化版本的参数。对于这种情况,您可以发送字符串{"data":"hello world"}

如果您想快速查找WCF服务的预期格式,可以使用WCF 客户端,使用相同的合同/绑定/行为,并向服务器发送消息(并在小提琴手上捕捉它)。例如,下面的代码显示了一个类似于您的服务器,以及一个向其发送请求的客户端。

public class StackOverflow_7492678
{
    public class RequestMessage
    {
        public string data;
    }
    public class ResponseMessage
    {
        public string data;
    }
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        ResponseMessage GetData(RequestMessage message);
    }
    public class Service : ITest
    {
        public ResponseMessage GetData(RequestMessage message)
        {
            return new ResponseMessage { data = message.data };
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        var endpoint = host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "");
        endpoint.Behaviors.Add(new WebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new WebHttpBinding(), new EndpointAddress(baseAddress));
        factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
        ITest proxy = factory.CreateChannel();

        Console.WriteLine(proxy.GetData(new RequestMessage { data = "mydata" }).data);

        ((IClientChannel)proxy).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}