【问题标题】:Receiving a large string in WCF service在 WCF 服务中接收大字符串
【发布时间】:2015-03-04 15:53:09
【问题描述】:

以下是我的服务合同

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/SavePrint?seq={seq}", BodyStyle = WebMessageBodyStyle.Bare)]
bool SavePrint(int seq, string print_lines);

字符串总是超过 3000 个字符,所以我不能在 URL 中传递它。

我正在尝试使用 WebClient 类上传。

WebClient client = new WebClient();
client.Headers["Content-type"] = "application/xml";
client.UploadString(baseURLTxtBox.Text + "/SavePrint?seq=1", LongStringHere);

当我尝试使用 WebClient 类的 UploadString 方法传递它时,服务失败并出现错误 There was an error checking start element of object of type System.String. The data at the root level is invalid. Line 1, position 1.

我假设是因为它被认为是 XML,所以我将我的字符串包装在 XML 中

<string xmlns="">LongStringHere</string>

然后我得到错误

无法使用根名称“字符串”和根名称空间“”反序列化 XML 正文(对于操作“SavePrint”和合同(“IPrintAPI”, 'http://tempuri.org/')) 使用 DataContractSerializer。确保 将 XML 对应的类型添加到已知类型集合中 服务。

我不知道我应该如何将字符串添加到已知类型集合中。

【问题讨论】:

    标签: c# wcf rest serialization http-post


    【解决方案1】:

    包装 "&lt;string&gt;&lt;/string&gt;" 不是编码 xml 的正确方法。 并且不确定为什么要使用 xml 进行编码....如果字符串不是 xml。

    http://www.w3.org/TR/html401/interact/forms.html#form-content-type

    不管....试试

    string url = baseURLTxtBox.Text;
    
    using(WebClient client = new WebClient())
    {
        System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
        nvc.Add("ParameterOne", "!@#$%^&*() Anything Any Characters Here");
        nvc.Add("ParameterTwo", LongString);
        byte[] responsebytes = client.UploadValues(url, "POST", nvc);
        string responsebody = Encoding.UTF8.GetString(responsebytes);
    }
    

    追加:

     [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "Mod?ParameterOne={ParameterOne}&ParameterTwo={ParameterTwo}")]
        bool SavePrint(string ParameterOne, string ParameterTwo);
    

    追加:

    现在尝试增加您的 maxReceivedMessageSize。

    <endpoint
              address  = "http://somethinghere"
        binding  = "basicHttpBinding" bindingConfiguration="BasicHttpEndpointBinding"
        contract = "MyIService" >
    </endpoint>
    
      <basicHttpBinding>
    <binding name="BasicHttpEndpointBinding"
       maxBufferSize="9000000"
       maxReceivedMessageSize="9000000"                      >
      <security mode = "None">
      </security>
    </binding>
    

    【讨论】:

    • 我的服务合同需要什么才能接受这个?目前不匹配。
    • 进行了编辑。我没有把它完善起来,只是向你展示这个想法/概念。让一两个字符串正常工作,然后调整以匹配您的确切签名。
    • 好的,但这无济于事。您只是将字符串添加到 URL 中。由于要发送的字符串的大小,我无法执行此操作。
    • 它是否适用于小字符串?我添加了一个“maxReceivedMessageSize”提示。首先让它使用一个小字符串。然后尝试调整 maxReceivedMessageSize 设置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多