Sebastian Xavier
Sebastian Xavier

Reputation: 2599

Exception in self host wcf service - The type initializer for 'System.ServiceModel.Diagnostics.TraceUtility' threw an exception

I have got the following exception, when I tried to port an existing IIS-based REST service to a self-hosted one.

The type initializer for 'System.ServiceModel.Diagnostics.TraceUtility' threw an exception.

I was following Self-hosted WCF REST service to port my existing code, before successfully testing the sample code given in this.

My Inner exception is given below.

Enter image description here

Now after commenting out the whole <configSections> tag, it throws another exception:

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

Here is my configuration file:

<?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>

Here is my interface:

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

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

Why is it throwing this exception?

Upvotes: 1

Views: 7561

Answers (1)

Pranav Singh
Pranav Singh

Reputation: 20101

Based on your actual inner exception,

Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element.

The cause of problem is <startup>..</startup> section, if <configSections> is present in web.config it must be first child of root element. Moving <startup>..</startup> section after <configSections> will resolve your problem.

  1. Uncomment <configSections> element.

  2. Move <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup> section below the <configSections>...</configSections> section.


Update:

For exception "The contract name 'SelfHostedRESTService.IService' could not be found in the list of contracts implemented by the service 'Service'."

Please correct the namespace used, its mismatch in namespace used in interface & web.config.

In Contract: namespace Contracts

In Web.config: SelfHostedRESTService.IService

Either,

  • Change namespace to SelfHostedRESTService in Interface

OR Alternatively

  • Use Contracts.IService in web.config.

Update 2 For Exception "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'." Seems you are using some variable named 'strInput' of type 'System.IO.Stream', which directly can't be serialized. Try serialize to string & then deserialize at other end.

One useful link is : http://www.techques.com/question/1-5241661/WCF-Complex-JSON-INPUT-Error-(not-convertible-by-QueryStringConverter)

Hope it helps.

Upvotes: 3

Related Questions