【问题标题】:Exception in self host wcf service - The type initializer for 'System.ServiceModel.Diagnostics.TraceUtility' threw an exception自托管 wcf 服务中的异常 - “System.ServiceModel.Diagnostics.TraceUtility”的类型初始化程序引发异常
【发布时间】:2014-07-19 19:16:27
【问题描述】:

当我尝试将现有的基于 IIS 的 REST 服务移植到自托管服务时,出现以下异常。

'System.ServiceModel.Diagnostics.TraceUtility' 的类型初始化程序引发了异常。

在成功测试本文中给出的示例代码之前,我正在关注 Self-hosted WCF REST service 移植我现有的代码。

下面给出了我的内部异常。

现在在注释掉整个 <configSections> 标记后,它会抛出另一个异常:

在服务“Service”实施的合同列表中找不到合同名称“SelfHostedRESTService.IService”

这是我的配置文件:

<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>

  <!--<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
          <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>-->

  <!--<log4net>
    <appender type="log4net.Appender.RollingFileAppender" name="DebugLog">
      <file value="C:\\TestProj\\Info.txt" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionpattern value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <appender type="log4net.Appender.RollingFileAppender" name="RestServiceLog">
      <file value="C:\\TestProj\\Error.txt" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionpattern value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <appender type="log4net.Appender.RollingFileAppender" name="bmitWarningLog">
      <file value="C:\\TestProj\\PingResult.txt" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionpattern value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <logger name="DebugLoggerClass">
      <level value="DEBUG" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1024KB" />
      <staticLogFileName value="true" />
      <param value="DEBUG" name="Threshold" />
      <appender-ref ref="DebugLog" />
    </logger>
    <logger name="SelfHostedRESTService">
      <level value="ERROR" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1024KB" />
      <staticLogFileName value="true" />
      <param value="ERROR" name="Threshold" />
      <appender-ref ref="RestServiceLog" />
    </logger>
    <logger name="WarningLoggerClass">
      <level value="WARN" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1024KB" />
      <staticLogFileName value="true" />
      <param value="WARN" name="Threshold" />
      <appender-ref ref="bmitWarningLog" />
    </logger>
  </log4net>-->

  <appSettings/>
  <connectionStrings/>
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpSoap" />
        <add name="HttpGet" />
        <add name="HttpPost" />
      </protocols>
    </webServices>

    <compilation debug="true">
      <assemblies>
        <add assembly="System.Core, Version=4.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>

    <authentication mode="Windows"/>

    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </controls>
    </pages>
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
    <identity impersonate="false" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v4.0"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </handlers>
  </system.webServer>

  <system.serviceModel>

    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IService" closeTimeout="10:01:00" openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00"
                 bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="10:10:00" enabled="false" />
        </binding>
      </wsHttpBinding>
    </bindings>

    <services>
      <service name="SelfHostedRESTService.Service" behaviorConfiguration="SelfHostedRESTService.RestServiceBehavior">
        <endpoint address="SelfHostedRESTService.Service" binding="webHttpBinding" contract="SelfHostedRESTService.IService" behaviorConfiguration="web">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="SelfHostedRESTService.RestServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

  </system.serviceModel>

</configuration>

这是我的界面:

namespace Contracts
{
    [ServiceContract]
    public interface IService
    {
        [XmlSerializerFormat]
        [OperationContract]
        [WebGet]
        XmlDocument postGeneralXMLDocument(Stream strInput);

        [OperationContract]
        [WebInvoke]
        string PostMessage(string inputMessage);
    }
}

为什么会抛出这个异常?

【问题讨论】:

  • 我之前看到过这个问题;我在 app.config 中的 Servicebehaviors 标签很好。
  • 你有没有发现异常并查看了它的内部异常?
  • 现在我添加了异常处理并更新了问题。无论如何,我只有一个 并且我现在已经对其进行了评论。现在我有一个新的异常“在服务'Service'实现的合同列表中找不到合同名称'SelfHostedRESTService.IService'。”
  • 该错误与 WCF 或 TraceUtility 无关。 TraceUtility 的静态 ctor 只是第一个遇到问题的代码。您的“app.config”在结构上无效(它在内部异常的文本中说明)。您似乎有不止一个 configSections 元素。您也可以发布 app.config 文件的内容,或者只是尝试自行更正。

标签: c# wcf rest


【解决方案1】:

根据你的实际内心异常,

Only one &lt;configSections&gt; element allowed per config file and if present must be the first child of the root &lt;configuration&gt; element.

问题的原因是&lt;startup&gt;..&lt;/startup&gt; 部分,如果&lt;configSections&gt; 存在于web.config 中,它必须是根元素的第一个子元素。在&lt;configSections&gt; 之后移动&lt;startup&gt;..&lt;/startup&gt; 部分将解决您的问题。

  1. 取消注释&lt;configSections&gt; 元素。

  2. &lt;startup&gt;&lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/&gt;&lt;/startup&gt; 部分移至&lt;configSections&gt;...&lt;/configSections&gt; 部分下方。


更新

对于异常"The contract name 'SelfHostedRESTService.IService' could not be found in the list of contracts implemented by the service 'Service'."

请更正使用的命名空间,它在接口和 web.config 中使用的命名空间不匹配。

合同中:namespace Contracts

在 Web.config 中:SelfHostedRESTService.IService

要么,

  • 在接口中将命名空间更改为SelfHostedRESTService

或者或者

  • 在 web.config 中使用 Contracts.IService

更新 2 对于异常"Operation 'postGeneralXMLDocument' in contract 'IService' has a query variable named 'strInput' of type 'System.IO.Stream', but type 'System.IO.Stream' is not convertible by 'QueryStringConverter'. Variables for UriTemplate query values must have types that can be converted by 'QueryStringConverter'." 似乎您正在使用一些名为“strInput”的变量,类型为“System.IO.Stream”,无法直接序列化。尝试序列化为字符串,然后在另一端反序列化。

一个有用的链接是: http://www.techques.com/question/1-5241661/WCF-Complex-JSON-INPUT-Error-(not-convertible-by-QueryStringConverter)

希望对你有帮助。

【讨论】:

  • 我按照你的建议做了。但得到了同样的例外。请查看我更新的问题和新异常“在服务'Service' 实施的合同列表中找不到合同名称'SelfHostedRESTService.IService'。”
  • 你取消了&lt;configSections&gt;的注释吗?
  • 是的,并移到上方以制作第一个元素。
  • 它与以前的问题完全不同。请显示您的服务合同界面,它与配置和实际文件/方法名称不匹配有关。
  • @SebastianXavier ,更新了问题解决方案的答案。
猜你喜欢
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
相关资源
最近更新 更多