23

是否可以在序列化/反序列化实体时覆盖默认的 WCF DataContractSerializer 行为并改用 JSON.NET?

我有以下处理城市实体的服务合同。出于设计原因,City 实体具有 IsReference=true,因此默认的 DataContractSerializer 会引发错误。

对于“GET”方法,我可以使用 JsonConvert.DeserializeObject 来处理这种情况,但使用“PUT、POST、DELETE”方法时,DataContractSerializer 具有优先权,并且无​​法抱怨 IsReference 实体无法序列化。

我找到了这篇文章来实现 IOperationBehavior 并提供我自己的序列化器,但我不知道如何将 Json.NET 与它集成。我相信应该有更直接的方法来解决这个问题。

我将不胜感激有关此方案的任何帮助或指导,或对其他方法的建议。

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class CityService
{
    [Description("Get all Cities")]  
    [WebGet(UriTemplate = "")]
    public Message Cities()
    {

    }

    [Description("Allows the details of a single City to be updated.")]
    [WebInvoke(UriTemplate = "{code}", Method = "PUT")]
    public Message UpdateCity(string code, City city)
    {
    }
}

非常感谢

霍萨姆

4

3 回答 3

23

使用扩展编码器和序列化器(参见http://msdn.microsoft.com/en-us/library/ms733092.aspx)或其他扩展 WCF 的方法(DataContractSerializerOperationBehavior如解决办法。

如果您已经使用Messagetype 来返回使用 WCF4 的结果,您可以执行以下操作:

public Message UpdateCity(string code, City city)
{
    MyResponseDataClass message = CreateMyResponse();
    // use JSON.NET to serialize the response data
    string myResponseBody = JsonConvert.Serialize(message);
    return WebOperationContext.Current.CreateTextResponse (myResponseBody,
                "application/json; charset=utf-8",
                Encoding.UTF8);
}

如果出现错误(如HttpStatusCode.UnauthorizedHttpStatusCode.Conflict)或在其他情况下需要设置 HTTP 状态码(如HttpStatusCode.Created),您可以继续使用WebOperationContext.Current.OutgoingResponse.StatusCode.

作为替代方案,您也可以返回一个Stream(参见http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspxhttp://msdn. microsoft.com/en-us/library/ms732038.aspx)而不是Message返回任何数据而无需 Microsoft JSON 序列化程序进行额外的默认处理。如果是 WCF4,您可以使用CreateStreamResponse(参见http://msdn.microsoft.com/en-us/library/dd782273.aspx)而不是CreateTextResponse. 如果您将使用此技术产生响应,请不要忘记在写入流后将流位置设置为 0。

于 2010-06-28T09:50:59.827 回答
1

您是否有某些原因要专门使用 Json.NET 库。如果要返回 JSON,为什么不直接使用 WebGet 和 WebInvoke 属性中的 ResponseFormat 属性呢?

[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]

大多数情况下应该这样。您正在运行哪个版本的 WCF?您返回 Message 类型而不是实际类型的任何原因?

于 2010-06-26T12:53:47.860 回答
-2

在服务行为的服务 Web 配置中定义它:

<endpointBehaviors>
   <behavior name="restfulBehavior">
      <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
      <!--<enableWebScript />-->
   </behavior>
</endpointBehaviors>

或在您的接口的操作合同中

[OperationContract]
[WebInvoke(Method = "GET", 
           UriTemplate = "/advertisements/{app_id}/{access_token}/{genero}/{age}", 
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json, 
           BodyStyle = WebMessageBodyStyle.Wrapped)]
于 2018-02-05T00:23:43.930 回答