POST上的WCF Restful Service异常无法识别的charSet' Windows-1252'在contentType中

时间:2014-06-25 12:41:46

标签: c# wcf rest character-encoding web-config

我创建了一个WCF Restful Service,在大多数情况下都可以正常工作:

[OperationContract(Name = "OrderResponse")]
[WebInvoke(Method = "POST", UriTemplate = "OrderResponse")]
void PostOrderResponse(Stream ordata);

但是,如果传入请求的内容类型设置为以下内容:

"text/xml; charset=Windows-1252"

客户端对api的POST获取HTTP响应400,并且以下内容显示在wcf跟踪日志中:

The default content type mapper selected the request format, 'Xml', given the request's content-type, 'text/xml; charset=Windows-1252'.

Unrecognized charSet 'Windows-1252' in contentType.

我很确定在调用任何代码之前会抛出错误,因为后面的代码会将响应设置为HTTP 202或406,具体取决于发送的内容或是否抛出任何错误:

    public void PostOrderResponse(Stream ordata)
    {
        try
        {
            // convert Stream Data to byte array
            using (var streamReader = new MemoryStream())
            {
                ordata.CopyTo(streamReader);
                data = streamReader.ToArray();
            }
            //if no data reject (http response)
            if (data.Length == 0)
            {
                SetResponseHttpStatus(HttpStatusCode.NotAcceptable);
            }
            else
            {   //convert byte[] to string
                xmlString = enc.GetString(data);
                conl = new SqlConnection(strConnString);
                conl.Open();
                SqlCommand cmdl = new SqlCommand("Insert_MSXML_MS_POR", conl);
                cmdl.CommandType = CommandType.StoredProcedure;
                cmdl.Parameters.Add(new SqlParameter("@DATA", xmlString));
                SqlDataReader sdrl = cmdl.ExecuteReader();
                sdrl.Close();
                conl.Close();

                SetResponseHttpStatus(HttpStatusCode.Accepted);
            }
        }
        catch
        {
            SetResponseHttpStatus(HttpStatusCode.NotAcceptable);
        }
        data = null;
    }

相关的Web.config数据:

<services>
  <service name="MWHMSXML_v1.MSXML" behaviorConfiguration="MSXML_Connect" >
    <endpoint address="" binding="webHttpBinding" contract="MWHMSXML_v1.IMSXML" bindingConfiguration="secureHttpBinding" behaviorConfiguration="webHttp" />
    <endpoint name="mexHttpsBinding" address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
  </service>
</services>

<bindings>

    <webHttpBinding>
        <binding name="secureHttpBinding">
            <security mode="Transport">
                <transport clientCredentialType="None"/>
            </security>
        </binding>
    </webHttpBinding>

</bindings>

我是否需要在web.config文件中添加内容以接受Window-1252字符集或如何克服此错误?

修改 我想我越来越近,我按照说明等创建了一个customtextmessageencoder,它似乎正在努力。查看跟踪日志后,请求(使用“Windows-1252”编码)命中正确的端点,但在打开“System.ServiceModel.InstanceContext”后出现以下错误:

Incoming message for operation 'OrderResponse' (contract 'IMSXML' with namespace 'MWHMSXML_v1')does not contain a WebBodyFormatMessageProperty. This can be because a WebContentTypeMapper or a WebMessageEncodingBindingElement has not been configured on the binding. See the documentation of WebContentTypeMapper and WebMessageEncodingBindingElement for more details.

我觉得这与我的web.config有关,相关的部分在这里:

<service name="MWHMSXML_v1.MSXML" behaviorConfiguration="MSXML_Connect" >
    <endpoint address="" binding="customBinding" contract="MWHMSXML_v1.IMSXML "bindingConfiguration="customHttpBinding" behaviorConfiguration="webEndpoint"/>
<endpoint name="mexHttpsBinding" address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>

<customBinding>
    <binding name="customHttpBinding" transferMode="Buffered" maxReceivedMessageSize="10485760">
        <customTextMessageEncoding encoding="Windows-1252" mediaType="text/Xml" messageVersion="None"/>
    <httpsTransport manualAddressing="true" />
    </binding>
</customBinding>

<bindingElementExtensions>
    <add name="customTextMessageEncoding" type=" MWHMSXML_v1.CustomTextMessageEncodingBindingSection, MWHMSXML_v1" />
</bindingElementExtensions>

<serviceBehaviors>
    <behavior name="MSXML_Connect"> <serviceCredentials> <serviceCertificate findValue="*.myurl.com" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /> </serviceCredentials> <serviceMetadata httpsGetEnabled="false" /><serviceDebug includeExceptionDetailInFaults="true"/></behavior>  </serviceBehaviors>

我搜索过&amp;搜索但无法找到任何有助于上述错误的信息。

1 个答案:

答案 0 :(得分:1)

根据此处的官方文档:Choosing a Message Encoder,WCF的默认TextMessageEncoder仅支持UTF-8,UTF-16:

  

TextMessageEncodingBindingElement和   MtomMessageEncodingBindingElement仅支持UTF8和UTF16   Unicode(big-endian和little-endian)编码。如果是其他编码   是必需的,例如UTF7或ASCII,必须使用自定义编码器。   有关自定义编码器示例,请参阅自定义消息编码器。

还有一个指向自定义消息编码器示例的链接:Custom Message Encoder: Custom Text Encoder(它使用ISO-8859-1编码,但您明白了这一点)

另请参阅此博文:Text Encoding and WCF