简体   繁体   English

使用webHttpBinding将对象序列化为WCF请求的主体

[英]Serializing an object into the body of a WCF request using webHttpBinding

I have a WCF service exposed with a webHttpBinding endpoint. 我有一个公开了webHttpBinding端点的WCF服务。

[OperationContract(IsOneWay = true)]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, 
    BodyStyle = WebMessageBodyStyle.Bare, 
    UriTemplate = "/?action=DoSomething&v1={value1}&v2={value2}")]
void DoSomething(string value1, string value2, MySimpleObject value3);

In theory, if I call this, the first two parameters (value1 & value 2) are taken from the Uri and the final one (value3) should be deserialized from the body of the request. 从理论上讲,如果我这样称呼,则前两个参数(值1和值2)取自Uri,最后一个参数(值3)应从请求正文中反序列化。

Assuming I am using Json as the RequestFormat, what is the best way of serialising an instance of MySimpleObject into the body of the request before I send it ? 假设我使用Json作为RequestFormat,在发送请求之前将MySimpleObject实例序列化到请求正文的最佳方法是什么? This, for instance, does not seem to work : 例如,这似乎不起作用:

HttpWebRequest sendRequest = (HttpWebRequest)WebRequest.Create(url);
sendRequest.ContentType = "application/json";
sendRequest.Method = "POST";
using (var sendRequestStream = sendRequest.GetRequestStream())
{
    DataContractJsonSerializer jsonSerializer = 
        new DataContractJsonSerializer(typeof(MySimpleObject));
    jsonSerializer.WriteObject(sendRequestStream, obj);
    sendRequestStream.Close();
}
sendRequest.GetResponse().Close();

One thing I'd do differently is to put the WebResponse into a using block: 我要做的另一件事是将WebResponse放入using块中:

using (var response = sendRequest.GetResponse())
{
}

I'd be concerned about what happens if the Close throws an exception in your code. 我担心如果Close在您的代码中引发异常会发生什么。

Also, are you logging exceptions? 另外,您是否正在记录异常? You might want to try: 您可能要尝试:

try
{
    using (var response = sendRequest.GetResponse())
    {
    }
}
catch (Exception ex) {
    Console.WriteLine(ex.ToString()); // Or however you want to display it
    throw;
}

This will ensure that you know of any problems with the response (like a non-200 HTTP status). 这样可以确保您知道响应的任何问题(例如非200 HTTP状态)。

I now have this working using both Json serialization (via both the DataContractJsonSerializer and Json.Net) and using the XmlSerializer. 现在,我既使用Json序列化(通过DataContractJsonSerializer和Json.Net)又使用XmlSerializer进行工作。

The odd thing is that the RequestFormat = WebMessageFormat.Xml property in the web invoke attribute seems to be ignored, ie inbound messages seem to be deserialized from xml or json regardless of this setting. 奇怪的是,Web调用属性中的RequestFormat = WebMessageFormat.Xml属性似乎被忽略,即无论此设置如何,入站消息似乎都从xml或json反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM