WCF Web Service not working after IIS restart - wcf

I have a web service running on IIS 7.5
Whenever I restart the IIS or the AppPool of the website this web service is running I am getting the error message below. Then I found out that, if I change the complilation version (either from 4.5 to 4.0 or if it is 4.0 to 4.5) and save the web.config file then it starts working regularly. This is really weird. Can anybody help me on this please.
web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
<connectionStrings>
<add name="NetDBEntities" connectionString="metadata=res://*/EFatura.csdl|res://*/EFatura.ssdl|res://*/EFatura.msl;provider=System.Data.SqlClient;provider connection string="data source=***********;initial catalog=*****;persist security info=True;user id=sa;password=***************;MultipleActiveResultSets=True;App=NSEfatLib"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.serviceModel>
<services>
<service name="NSEfatLib.NSEfatEntryPoint">
<endpoint address="Cari" binding="basicHttpBinding" bindingConfiguration=""
name="Cari" contract="NSEfatLib.ICari" />
<endpoint address="Stok" binding="basicHttpBinding" bindingConfiguration=""
name="Stok" contract="NSEfatLib.IStok" />
<endpoint address="FaturaIslemler" binding="basicHttpBinding"
bindingConfiguration="" name="FaturaIslemler" contract="NSEfatLib.IFaturaIslemler" />
<endpoint address="DefterIslemler" binding="basicHttpBinding"
bindingConfiguration="" name="DefterIslemler" contract="NSEfatLib.IDefterIslemler" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Error Message:
The type 'NSEfatLib.NSEfatEntryPoint', provided as the Service
attribute value in the ServiceHost directive, or provided in the
configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found. Description: An unhandled exception occurred during the
execution of the current web request. Please review the stack trace
for more information about the error and where it originated in the
code.
Exception Details: System.InvalidOperationException: The type
'NSEfatLib.NSEfatEntryPoint', provided as the Service attribute value
in the ServiceHost directive, or provided in the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The type 'NSEfatLib.NSEfatEntryPoint',
provided as the Service attribute value in the ServiceHost directive,
or provided in the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found.]
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses) +122516
System.ServiceModel.HostingManager.CreateService(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1451
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo
serviceActivationInfo, EventTraceActivity eventTraceActivity) +76
System.ServiceModel.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) +901
[ServiceActivationException: The service '/Service.svc' cannot be
activated due to an exception during compilation. The exception
message is: The type 'NSEfatLib.NSEfatEntryPoint', provided as the
Service attribute value in the ServiceHost directive, or provided in
the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found..] System.Runtime.AsyncResult.End(IAsyncResult result)
+650220 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) +210733
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult
ar) +282
Event Log Entry:
System.ServiceModel.ServiceHostingEnvironment+HostingManager/62476613
System.ServiceModel.ServiceActivationException: The service
'/Service.svc' cannot be activated due to an exception during
compilation. The exception message is: The type
'NSEfatLib.NSEfatEntryPoint', provided as the Service attribute value
in the ServiceHost directive, or provided in the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found.. ---> System.InvalidOperationException: The type
'NSEfatLib.NSEfatEntryPoint', provided as the Service attribute value
in the ServiceHost directive, or provided in the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found. at
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo
serviceActivationInfo, EventTraceActivity eventTraceActivity) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) --- End
of inner exception stack trace --- at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) at
System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String
relativeVirtualPath, EventTraceActivity eventTraceActivity) w3wp
5028

Interestingly above error was fired when the web service was precompiled. I tried the service to run regularly (without precomopiling) and the issue is not appearing anymore.
I was using a library within the web service, so practically the web service itself did not have any code at all. Maybe that is the reason. Anyways, as there is no code, no precompilation is fine too.

Related

WCF customUserNamePasswordValidatorType error - Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies

I have created a simply WCF web service and require WCF Security with username/password added to the service and have read through the following MS documentation https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-a-custom-user-name-and-password-validator to try and do so.
However, I am getting the error below when I run the project and go to http://localhost:50533/Service.svc:
Server Error in '/' Application.
Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'CustomUserNameValidator' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = CustomUserNameValidator
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: CustomUserNameValidator | Domain ID: 6
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/
LOG: Initial PrivatePath = C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\web.config
LOG: Using host configuration file: C:\Users\xxxx\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.EXE.
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +71
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +41
System.Type.GetType(String typeName, Boolean throwOnError) +35
System.ServiceModel.Configuration.UserNameServiceElement.ApplyConfiguration(UserNamePasswordServiceCredential userName) +356
System.ServiceModel.Configuration.ServiceCredentialsElement.ApplyConfiguration(ServiceCredentials behavior) +128
System.ServiceModel.Configuration.ServiceCredentialsElement.CreateBehavior() +165
System.ServiceModel.Description.ConfigLoader.LoadBehaviors(ServiceModelExtensionCollectionElement`1 behaviorElement, KeyedByTypeCollection`1 behaviors, Boolean commonBehaviors) +204
System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress, Boolean skipHost) +13502205
System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection) +74
System.ServiceModel.ServiceHostBase.ApplyConfiguration() +188
System.ServiceModel.ServiceHost.ApplyConfiguration() +65
System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses) +188
System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses) +49
System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses) +153
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) +34
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +538
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1489
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +53
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +666
[ServiceActivationException: The service '/Service.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified..]
System.Runtime.AsyncResult.End(IAsyncResult result) +513025
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +182
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +12
System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +161
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +128
I have noticed this error only appears due to adding the following into my Web.Config file
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
I've modified the value in customUserNamePasswordValidatorType numerous times to try and fix it but the error still comes up or a similar one.
See below for the full Web.Config file.
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
<pages>
<namespaces>
<add namespace="System.Runtime.Serialization"/>
<add namespace="System.ServiceModel"/>
<add namespace="System.ServiceModel.Web"/>
</namespaces>
</pages>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Binding1">
<security mode="Transport">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
The Code is simply the default WCF Service code you get out of the box when creating a new WCF Service project in Visual Studio and I've just added a new CustomUserNameValidator class.
If you want to see this class, here is the code for it:
Imports System.IdentityModel.Selectors
Public Class CustomUserNameValidator
Inherits UserNamePasswordValidator
Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
If userName Is Nothing OrElse password Is Nothing Then
Throw New ArgumentNullException()
End If
If Not (userName = "user" AndAlso password = "pass123") Then
Throw New FaultException("Unknown Username or Incorrect Password")
End If
End Sub
End Class
Also, this is all that shows in Properties for the file.
If you can please help with the error, that would be very much appreciated.
You must to be sure that the “Build Action” on the “CustomUserNameValidator.vb” Properties is set to “Compile”.
It seems to be set on “Content” based on what you are describing.
The image shows how you can do that or take a look here:
https://learn.microsoft.com/en-us/visualstudio/ide/build-actions?view=vs-2022
The reason I was getting the problem above was because I needed to set this in the web.config
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomUserNameValidator, App_Code" />
</serviceCredentials>
When I went to the following path on my machine, the only dll was App_Code.tjgywzog.dll so figured the assembly is just App_Code and then it just has to use the class name CustomUserNameValidator since my code is not using namespaces.

WCF Service running on localhost (debug) but failing at deployment

I have a WCF Service that works when i run it at localhost, using the WCF Test Client I can invoke it and get a result. I can also see it when I actually host it on the live server as it generates the methods on the test client and I can see the wsdl page when opened in Chrome.
But (because it always has a but) when I invoke it with WCF Test Client I get this error:
Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at IRp3Services.CreateTransaction(NewTransaction model) at Rp3ServicesClient.CreateTransaction(NewTransaction model)
I cant seem to understand why, I have tested it locally and works perfectly, here is the web config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="ConsultasSoap" />
<binding name="TransaccionesSoap" />
<binding name="SeguridadSoap" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://address/Rp3.Web.Credishop.Afiliados/consultas.asmx"
binding="basicHttpBinding" bindingConfiguration="ConsultasSoap"
contract="RP3Consultas.ConsultasSoap" name="ConsultasSoap" />
<endpoint address="http://address/Rp3.Web.Credishop.Afiliados/transacciones.asmx"
binding="basicHttpBinding" bindingConfiguration="TransaccionesSoap"
contract="RP3Transacciones.TransaccionesSoap" name="TransaccionesSoap" />
<endpoint address="http://address/Rp3.Web.Credishop.Afiliados/seguridad.asmx"
binding="basicHttpBinding" bindingConfiguration="SeguridadSoap"
contract="RP3Seguridad.SeguridadSoap" name="SeguridadSoap" />
</client>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpBinding" scheme="http" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
I am really at a loss here, I would love any input on what I am doing wrong here.

{error: (403) Forbidden."} WCF basicHttpBinding with Transport and Certificate Credential

I get the error "{"The remote server returned an error: (403) Forbidden."} The HTTP request was forbidden with client authentication scheme 'Anonymous'." when using basicHttpBinding with Transport security and certificate credential. My service is in amazon ec2 instance and my client app remotely connect to it over the internet. I am able to connect to the wcf service if my Transport credential is set to "None" in both the web.config of the service and app.config of the client. My service certificate is like "www.example.com" is installed on amazon ec2 "local machine store" and "Personal Folder". My client app certificate is just a self-signed certificate which I installed to its "local machine and Personal Folder" and also to the "Trusted People store" in the amazon ec2 instance where my wcf service is. I have also setup "https" to my IIS site bindings and I can reach the site through like "https://www.example.com"
Below is the web.config, app.config, and the code I have on the client app.
Service Web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_Config" >
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="MyProject.MyService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBinding_Config"
contract="MyService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" trustedStoreLocation="LocalMachine"/>
</clientCertificate>
<serviceCertificate findValue="www.example.com" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Client app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_Config" >
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://www.example.com/sub/Service1.svc"
binding="basicHttpBinding" bindingConfiguration="basicHttpBinding_Config"
contract="ServiceReference1.MyService" name="BasicHttpBinding_MyService" />
</client>
<behaviors>
<endpointBehaviors>
<behavior>
<clientCredentials>
<clientCertificate findValue="clientKey"
storeLocation="LocalMachine"
storeName="My"
x509FindType="FindBySubjectName" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Client App Console Code:
static void Main(string[] args)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
ServiceReference1.MyServiceClient client = new ServiceReference1.MyServiceClient();
string[] a = client.GetMethods(ref mh);
foreach (string s in a)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
The Diagnostic Tracing returns below:
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
<EventID>131077</EventID>
<Type>3</Type>
<SubType Name="Critical">0</SubType>
<Level>1</Level>
<TimeCreated SystemTime="2018-11-16T21:50:58.8220239Z" />
<Source Name="System.ServiceModel" />
<Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" />
<Execution ProcessName="ConsoleApplication1" ProcessID="22220" ThreadID="1" />
<Channel />
<Computer>DESKTOP-RPNI11M</Computer>
</System>
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical">
<TraceIdentifier>UnhandledException</TraceIdentifier>
<Description>Unhandled exception</Description>
<AppDomain>ConsoleApplication1.exe</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.Security.MessageSecurityException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The HTTP request was forbidden with client authentication scheme 'Anonymous'.</Message>
<StackTrace>
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory`1 factory)
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication1.ServiceReference1.IOD_V416.GetMethods(GetMethodsRequest request)
at ConsoleApplication1.ServiceReference1.OD_V416Client.ConsoleApplication1.ServiceReference1.IOD_V416.GetMethods(GetMethodsRequest request) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 72017
at ConsoleApplication1.ServiceReference1.OD_V416Client.GetMethods(MultiSpeakMsgHeader& MultiSpeakMsgHeader) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 72023
at ConsoleApplication1.Program.Main(String[] args) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Program.cs:line 43
</StackTrace>
<ExceptionString>System.ServiceModel.Security.MessageSecurityException: The HTTP request was forbidden with client authentication scheme 'Anonymous'. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory`1 factory)
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication1.ServiceReference1.IOD_V416.GetMethods(GetMethodsRequest request)
at ConsoleApplication1.ServiceReference1.OD_V416Client.ConsoleApplication1.ServiceReference1.IOD_V416.GetMethods(GetMethodsRequest request) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 72017
at ConsoleApplication1.ServiceReference1.OD_V416Client.GetMethods(MultiSpeakMsgHeader& MultiSpeakMsgHeader) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 72023
at ConsoleApplication1.Program.Main(String[] args) in D:\Workfolder\Projects2\MyProject\WCF_App\MyService - Copy (3)\ConsoleApplication1\Program.cs:line 43</ExceptionString>
<InnerException>
<ExceptionType>System.Net.WebException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The remote server returned an error: (403) Forbidden.</Message>
<StackTrace>
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
</StackTrace>
<ExceptionString>System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</ExceptionString>
</InnerException>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
</ApplicationData>
</E2ETraceEvent>
I did look to other similar issues but none has solve it yet, I'm continuously searching for the right solutions, I appreciate any help or advice the community provides.
EDIT:
Probably better to use a sha2 cert:
makecert -len 2048 -r -a sha256 -sv private.pvk -n CN=yoursubjectname cert.cer
pvk2pfx -spc cert.cer -pvk private.pvk -pfx out.pfx
Install the private cert(.pfx) on the host, set in IIS app, and install the public cert on the client(.cer), you will have to install in both personal and trusted people stores.
EDIT: I think you also need to give your behavior a name in the host and client config and assign that behavior to your endpoints.
Host:
<behavior name="serviceBahavior">
<service name="MyProject.MyService" behaviorConfiguration="serviceBahavior">
Client:
<behavior name="clientBahavior">
<endpoint address="https://www.example.com/sub/Service1.svc"
binding="basicHttpBinding" bindingConfiguration="basicHttpBinding_Config"
contract="ServiceReference1.MyService" name="BasicHttpBinding_MyService" behaviorConfiguration="clientBahavior" />
I think since you are using <security mode="Transport"> you will need to make your mex as HTTPS:
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
Also set in your behavior the serviceMetadata
from:
<serviceMetadata httpGetEnabled="true"/>
to <serviceMetadata httpsGetEnabled="true"/>
Also, make sure your transport in the client config matches the host config:
<transport clientCredentialType="Certificate"/>
I found the following solution that works for this error I encountered.
First, I created a certificate as follows:
makecert -n "CN=MyRootSigningKey" -r -sv MyRootSigningKey.pvk MyRootSigningKey.cer
Second, I treat this as my root key and install it in my AWS service under the certificate store "Trusted Root Certification Authorities" using mmc.
Third, I created a self-signed cert using the root key "MyRootSigningKey" as follows:
makecert -sk MySignedKeyName -iv MyRootSigningKey.pvk -n "CN=MySignedKey" -ic MyRootSigningKey.cer -sr localmachine -ss my -sky exchange -pe
Last, I reference the self signed cert "MySignedKey" in my client app config like below:
<client>
<endpoint address="https://www.example.com/sub/Service1.svc" behaviorConfiguration="clientBehavior"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_MyService"
contract="ServiceReference1.MyService" />
</client>
<behaviors>
<endpointBehaviors>
<behavior name="clientBehavior">
<clientCredentials>
<clientCertificate findValue="MySignedKey"
storeLocation="LocalMachine"
storeName="My"
x509FindType="FindBySubjectName" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>

Getting the binding error in WCF. Cannot understand what it is.

Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http].
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http].
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http].]
System.ServiceModel.ServiceHostBase.MakeAbsoluteUri(Uri relativeOrAbsoluteUri, Binding binding, UriSchemeKeyedCollection baseAddresses) +12366396
System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress) +12363749
System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection) +67
System.ServiceModel.ServiceHostBase.ApplyConfiguration() +108
System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses) +192
System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses) +49
System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses) +151
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) +30
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +422
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +1461
System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +44
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +651
[ServiceActivationException: The service '/BulkEmailService.svc' cannot be activated due to an exception during compilation. The exception message is: Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http]..]
System.Runtime.AsyncResult.End(IAsyncResult result) +688590
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +190
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +359
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +148
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Here is my Web.config file. Please help.
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="WWDbConnect"
connectionString="Data Source=(dev0320);USER ID = scott; Password = t;Max Pool Size=200;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBindingWithNoSecurity" maxBufferPoolSize="524288" maxReceivedMessageSize="500000">
<security mode="Transport">
<transport clientCredentialType="Certificate" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client/>
<services>
<service name="WW.Common.Service.Impl.EmailService" behaviorConfiguration="BasicHttpBindingWithNoSecurity">
<host>
<baseAddresses>
<add baseAddress = "https://localhost:8270/Design_Time_Addresses/TestWcfEmailServiceLibrary/EmailService/" />
</baseAddresses>
</host>
<endpoint address="EmailService" binding="basicHttpBinding" contract="WW.Common.Service.Contract.IEmailService" />
<endpoint address="mex" binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingWithNoSecurity"
name="mexEndpoint" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="EmailService">
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true"/>
<serviceMetadata httpsGetEnabled="true" />
<serviceSecurityAudit auditLogLocation="Application"
suppressAuditFailure="true"
serviceAuthorizationAuditLevel="Success"
messageAuthenticationAuditLevel="Success" />
</behavior>
</serviceBehaviors>
</behaviors>
<diagnostics>
<messageLogging logEntireMessage="true"
maxMessagesToLog="3000"
logMessagesAtServiceLevel="true"
logMalformedMessages="false"
logMessagesAtTransportLevel="false" />
</diagnostics>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
you are using https in your base address, but your binding is basicHttpBinding. Looking at your config I am assuming you are planning to use certificates. I would recommend that you change your binding to WSHttpBinding
<endpoint address="test" binding="wsHttpBinding" contract="WW.Common.Service.Contract.IEmailService"/>
Alternately, if you want to use http only. change the base address to http as shown below. Note, I have also removed the binding configuration from your code
<service name="WW.Common.Service.Impl.EmailService">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8270/Design_Time_Addresses/TestWcfEmailServiceLibrary/EmailService/" />
</baseAddresses>
</host>
<endpoint address="EmailService" binding="basicHttpBinding" contract="WW.Common.Service.Contract.IEmailService" />
<endpoint address="mex" binding="basicHttpBinding"
name="mexEndpoint" contract="IMetadataExchange" />
</service>
I will also recommend that you read up on WCF bindings

WCF service working in iis 5.1 but not working in iis 6

I developed a WCF service and silverlight client, when I host this service in windows xp having iis 5.1, it is perfectly working as expected.
When i host in windows server 2003 R2 having iis 6, it is working for initial couple of minutes (approximately 20 mins) after that it stops working..
i am getting HTTP 500 when i access service.
The setting I have used are
Anonymous access and integrated authentication both are checked.
my service config is as follows
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="false"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="SilverlightApplication1.Web.GetData.customBinding0">
<binaryMessageEncoding/>
<httpTransport/>
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<services>
<service name="SilverlightApplication1.Web.GetData">
<endpoint address="" binding="customBinding" bindingConfiguration="SilverlightApplication1.Web.GetData.customBinding0" contract="SilverlightApplication1.Web.GetData"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
my silverlight client config is
<client>
<endpoint address="----/InternalBorrow/GetData.svc"
binding="customBinding" bindingConfiguration="CustomBinding_GetData"
contract="ServiceReference1.GetData" name="CustomBinding_GetData" />
</client>
can any body help me to trouble shoot my problem?
the exception i am getting is
System.ServiceModel.Activation.HostedAspNetEnvironment.ValidateHttpSettings(String virtualPath, Boolean isMetadataListener, Boolean usingDefaultSpnList, AuthenticationSchemes& supportedSchemes, ExtendedProtectionPolicy& extendedProtectionPolicy, String& realm)at System.ServiceModel.Channels.HttpChannelListener.ApplyHostedContext(String virtualPath, Boolean isMetadataListener)
at System.ServiceModel.Activation.HostedAspNetEnvironment.ApplyHostedContext(TransportChannelListener listener, BindingContext context)
at System.ServiceModel.Channels.HttpTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context)
at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context)
at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
at System.ServiceModel.ServiceHostBase.InitializeRuntime()
at System.ServiceModel.ServiceHostBase.OnBeginOpen()
at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open()
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
I experienced a similar issue when we were running a .NET 4.0 web application in the same app pool as web service configured to use a lower version of .NET. Make sure you are not mixing ASP .NET versions in the same application pool on the server.
Are there any errors or warnings showing up in the web server's event viewer logs that would provide you with more information about the issue?