在Web服务中,当我尝试序列化为JSON消息时,我收到"未找到密钥"异常

Dug*_*gan 0 .net c# wcf json

我有一个Web服务,它使用对System.ServiceModel.Dispatcher.SerializeReply消息的调用(特别是MultiplexingDispatchMessageFormatter实现).当我进行此调用时,我收到一个"未找到密钥"异常,我追溯到System.ServiceModel.Dispatcher.MultiplexingDispatchMessageFormatter中的一行,它正在尝试根据键获取"defaultContentType".

不幸的是我无法看到密钥是什么,但defaultContentType集合似乎没有任何项目.

要使SerializeReply正常工作,我需要做什么?

代码:

public System.ServiceModel.Channels.Message SerializeReply(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters, object result)
{
    System.Web.HttpRequest requestMessage = System.Web.HttpContext.Current.Request;

    string format = requestMessage.QueryString["format"];
    if (!string.IsNullOrEmpty(format) && string.Compare(format, "json", true) == 0)
    {
    return jsonResponseDispatchMessageFormatter.SerializeReply(messageVersion, parameters, result);
    }
    //[UNRELATED CODE]
}
Run Code Online (Sandbox Code Playgroud)

这是在System.ServiceModel.Dispatcher.MultiplexingDispatchMessageFormatter中爆炸的行(键是"json",defaultContentTypes没有条目):

outgoingResponse.ContentType = this.defaultContentTypes[key];
Run Code Online (Sandbox Code Playgroud)

我得到的例外:

System.Collections.Generic.KeyNotFoundException occurred
Message=The given key was not present in the dictionary.
Source=mscorlib
StackTrace:
   at System.ThrowHelper.ThrowKeyNotFoundException()
InnerException: 
Run Code Online (Sandbox Code Playgroud)

pea*_*lou 5

我遇到了这个问题并想出了如何使用好的'Reflector来修复它.原因是因为OutgoingResponse的ContentType为空.在针对jsonResponseDispatchMessageFormatter调用"SerializeReply"之前立即添加以下内容可能会起到作用:

WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
Run Code Online (Sandbox Code Playgroud)