且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 Json.Net 设置为 WCF REST 服务的默认序列化程序

更新时间:2022-12-04 17:00:48

Extended Encoders 和 Serializers 的用法(参见 http://msdn.microsoft.com/en-us/library/ms733092.aspx) 或其他扩展 WCF 的方法,例如使用 DataContractSerializerOperationBehavior有趣,但对于您的特殊问题,有更简单的解决方法.

The usage of Extending Encoders and Serializers (see http://msdn.microsoft.com/en-us/library/ms733092.aspx) or other methods of Extending WCF like usage of DataContractSerializerOperationBehavior is very interesting, but for your special problem there are easier solution ways.

如果您已经使用 Message 类型返回结果并使用 WCF4,您可以执行以下操作:

If you already use Message type to return the results an use WCF4 you can do something like following:

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.

In case of errors (like HttpStatusCode.Unauthorized or HttpStatusCode.Conflict) or in other situations when you need to set a HTTP status code (like HttpStatusCode.Created) you can continue to use 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.

As an alternative you can also return a Stream (see http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx and http://msdn.microsoft.com/en-us/library/ms732038.aspx) instead of Message to return any data without additional default processing by Microsoft JSON serializer. In case of WCF4 you can use CreateStreamResponse (see http://msdn.microsoft.com/en-us/library/dd782273.aspx) instead of CreateTextResponse. Don't forget to set stream position to 0 after writing in the stream if you will use this technique to produce the response.