修复WCF异常《System.ArgumentException: 已经存在名称为“UriTemplateMatchResults”的属性》

接口定义:

[OperationContract]
[WebInvoke(
    Method = "POST",
    UriTemplate = "AddUser/{userinfo}",
    BodyStyle = WebMessageBodyStyle.Bare,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
string AddUser(string userinfo);

问题描述:

- 传入参数的长度小于256时,正常。
- 传入参数的长度大于256时,返回 BadRequest 的异常信息。

一般来说,这是配置的传输参数的长度问题,不过配置文件中已配置了长度:

<bindings>
  <webHttpBinding>
    <binding name="webHttpBinding" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
    </binding>
  </webHttpBinding>
</bindings>

<services>
  <service behaviorConfiguration="webHttpBehavior" name="WebService">
    <endpoint address="web" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBinding" contract="IWebService" name="webservice"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:9999/service"/>
      </baseAddresses>
    </host>
  </service>

问题跟踪:

在配置文件中添加如下配置,以记录具体的错误信息到本地的svclog文件中:

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Warning" propagateActivity="true">
      <listeners>
        <add name="xml" />
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="F:\wcf.svclog" />
  </sharedListeners>
</system.diagnostics>

跟踪到的错误信息中有下面一句:

System.ArgumentException: 已经存在名称为“UriTemplateMatchResults”的属性。

问题处理:

这里提供一种最直接的解决方法时,直接屏蔽接口中的UriTemplate定义。

[OperationContract]
[WebInvoke(
    Method = "POST",
    //UriTemplate = "AddUser/{userinfo}",
    BodyStyle = WebMessageBodyStyle.Bare,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
string AddUser(string userinfo);

你可能感兴趣的:(exception,WCF)