在 IClientMessageFormatter.SerializeRequest (HTTP GET) 中撰写消息

本文关键字:消息 GET IClientMessageFormatter SerializeRequest HTTP | 更新日期: 2023-09-27 18:32:06

我正在使用WCF Extensibilty,我创建了一个通过Json-RPC序列化请求的IClientMessageFormatter。代码是这样的:

    public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
    {
        string jsonText = SerializeJsonRequestParameters(parameters);
        // Compose message
        Message message = Message.CreateMessage(messageVersion, _clientOperation.Action, new JsonRpcBodyWriter(Encoding.UTF8.GetBytes(jsonText)));
        message.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
        _address.ApplyTo(message);
        HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty();
        reqProp.Headers[HttpRequestHeader.ContentType] = "application/json";
        message.Properties.Add(HttpRequestMessageProperty.Name, reqProp);
        UriBuilder builder = new UriBuilder(message.Headers.To);
        builder.Query = string.Format("jsonrpc={0}", HttpUtility.UrlEncode(jsonText));
        message.Headers.To = builder.Uri;
        message.Properties.Via = builder.Uri;
        return message;
    }

我尝试使用 HttpRequestMessageProperty 强制 WCF 使用 GET http 谓词,但设置了以下内容:

reqProp.Method = "GET";

导致 WCF 引发 System.Net.ProtocolViolationException。谁能告诉我我做错了什么?

在 IClientMessageFormatter.SerializeRequest (HTTP GET) 中撰写消息

自己找到了答案!GET 谓词要求消息不包含正文:

    public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
    {
        string jsonText = SerializeJsonRequestParameters(parameters);
        // Compose message
        Message message = Message.CreateMessage(messageVersion, _clientOperation.Action);
        _address.ApplyTo(message);
        HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty();
        reqProp.Headers[HttpRequestHeader.ContentType] = "application/json";
        reqProp.Method = "GET";
        message.Properties.Add(HttpRequestMessageProperty.Name, reqProp);

        UriBuilder builder = new UriBuilder(message.Headers.To);
        builder.Query = string.Format("jsonrpc={0}", HttpUtility.UrlEncode(jsonText));
        message.Headers.To = builder.Uri;
        message.Properties.Via = builder.Uri;
        return message;
    }