WCF Security Mode TransportWithMessageCredential - c#

I've not a WCF service running as a windows service that I've converted to use the Custom UserNamePasswordValidator.
This all worked perfectly on the original setting of SecurityMode = "Transport".
However the only problem is that none of the faultexceptions would come back correctly.
I guessed this was because it needs to be a security mode of TransportWithMessageCredential.
The problem I have is when I set the security mode to be TransportWithMessageCredential the UserNamePasswordValidator validate method is now not hit.
Below is my app.config. Any advice would be greatly appreciated.
Thanks.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<!-- hidden -->
</connectionStrings>
<system.serviceModel>
<services>
<service name="ThisApp.Global.Service.ServiceImpl" behaviorConfiguration="serviceBehaviour">
<host>
<baseAddresses>
<add baseAddress="https://testapi.ThisApp.com" />
</baseAddresses>
</host>
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="TransportSecurity" contract="ThisApp.Global.Service.IServiceImpl" />
</service>
</services>
<!--WCF Service Binding Configurations-->
<bindings>
<wsHttpBinding>
<binding name="TransportSecurity">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="False" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="True"/>
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="ThisApp.Global.Service.Security.AuthorizationPolicy, ThisApp.Global.Service" />
</authorizationPolicies>
</serviceAuthorization>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ThisApp.Global.Service.Security.CustomUserNameValidator, ThisApp.Global.Service" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.diagnostics>
<trace autoflush="true" indentsize="2">
<listeners>
<add name="myListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="ThisApp Global API" />
</listeners>
</trace>
</system.diagnostics>
</configuration>

You need to include transport in the binding security section, thus:
<binding name="TransportSecurity">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
<transport clientCredentialType="Basic" />
</security>
</binding>

Related

WCF - HTTP request was aborted

I am new to WCF and trying to troubleshoot an error. I have a WCF service running on a remote server and am receiving an error when another WCF service tries to call it running in my localhost.
The HTTP request to [url to the service] was aborted. This may be due to the local channel being closed while the request was still in progress. If this behavior is not desired, then update your code so that it does not close the channel while request operations are still in progress.
I tried looking at the activity in the Microsoft Service Trace Viewer and the first error received is:
Failed to lookup a channel to receive an incoming message. Either the endpoint or the SOAP action was not found.
I can see the service is running, I can access it in the browser.
Can anyone help point me in the right direction of anything I can try? The service that I am trying to connect to is called LinkTable and I have added the relevant config files.
Client web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMyService" />
<binding name="BasicHttpBinding_IKeyLinkage" closeTimeout="00:25:00"
openTimeout="00:02:00" receiveTimeout="00:02:00" sendTimeout="00:02:00"
maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
<binding name="BasicHttpBinding_IMaintenance" />
</basicHttpBinding>
<wsHttpBinding>
<binding name="WSHttpBinding_L2" closeTimeout="00:25:00" openTimeout="00:02:00"
receiveTimeout="00:02:00" sendTimeout="00:02:00" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
</security>
</binding>
<binding name="wsHttpBinding_IProcessXML" closeTimeout="00:25:00"
openTimeout="00:02:00" receiveTimeout="00:02:00" sendTimeout="00:02:00"
maxReceivedMessageSize="2147483647" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http:/path/Service.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyService"
contract="NotificationService.IMyService" name="BasicHttpBinding_IMyService" />
<endpoint address="http://path/Maintenance.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMaintenance"
contract="MaintenanceService.IMaintenance" name="BasicHttpBinding_IMaintenance" />
<endpoint address="http://path/Services/KeyLinkage.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IKeyLinkage"
contract="KeyLinkageService.IKeyLinkage" name="BasicHttpBinding_IKeyLinkage" />
<endpoint address="https://path/Services/LinkTableService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_L2"
contract="LinkTable_L2.ILinkTableService" name="WSHttpBinding_ILinkTableService" />
</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="wsHttpBinding" scheme="http" bindingConfiguration="wsHttpBinding_IProcessXML"/>
</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>
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
<source name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
<source name="System.Runtime.Serialization" switchValue="Verbose,ActivityTracing">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="App_tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="Timestamp" />
</sharedListeners>
</system.diagnostics>
</configuration>
Server web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.serviceModel>
<client>
<endpoint address="http://path/Services/LinkTable.svc" binding="basicHttpBinding" bindingConfiguration="AppName_WCF_BasicHttpBinding" contract="LinkTableWCF.ILinkTable" name="BasicHttpBinding_ILinkTable" />
</client>
<services>
</service>
<service behaviorConfiguration="AppName_L2_WCF_Behavior" name="AppName_L2_WCF.Services.LinkTableService">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="AppName_L2_WCF_wsHttpBinding" contract="AppName_L2_WCF.ServiceContracts.ILinkTableService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="AppName_WCF_BasicHttpBinding" maxBufferPoolSize="819200" maxReceivedMessageSize="2147483647" />
</basicHttpBinding>
<wsHttpBinding>
<binding name="AppName_L2_WCF_wsHttpBinding" maxBufferPoolSize="819200" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="AppName_L2_WCF_Behavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="AppName_L2_WCF.Utils.ServiceAuthenticator, AppName_L2_WCF" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="wsHttpBinding" scheme="http" bindingConfiguration="AppName_L2_WCF_wsHttpBinding" />
</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>

RESTful windows authentication

I've set up a RESTful WCF web service on our server (IIS 8.5 running on Windows Server 2012 R2). I can connect remotely and run exposed methods no problem.
I get a problem when the method contains a connection to a database. Despite having windows authentication set up in IIS, the username passed through to the database is defaulting to the machine default, which is wrong.
I'm currently using this web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<identity impersonate="true"/>
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<system.serviceModel>
<services>
<service name="AriaRestFul2.Service1" behaviorConfiguration="AriaRestFul2.Service1Behavior">
<endpoint address="../Service1.svc" binding="webHttpBinding" contract="AriaRestFul2.IService1" behaviorConfiguration="webBehaviour" bindingConfiguration="restbinding">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="webHttpBinding" contract="IMetadataExchange" bindingConfiguration="restbinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="AriaRestFul2.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="restbinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
<system.webServer>
<httpErrors errorMode="Detailed" />
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false"/>
<directoryBrowse enabled="true" />
</system.webServer>
<connectionStrings>
<add name="AriaEntities" connectionString="metadata=res://*/Aria.csdl|res://*/Aria.ssdl|res://*/Aria.msl;provider=System.Data.SqlClient;provider connection string="data source=<instance>;initial catalog=Aria;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
The database I'm connecting to is through EF6. I'm using chrome as the client to pass in the URL to the service. I'm worried that this setup might require the credentials to be assigned in code in a client. If this is the case, is there anyway I can configure the service to just pass through the current user from the browser?

WCF used as service reference: how do it?

I've my RESTful service hosted here .
I can use it perfectly with get&post http request.
How can I use as "service reference" in a Visual Studio project? I have added it in my test project and I see the methods correctly, but, when I try to call on of them, I get the "could not find default endpoint element that references contract in the servicemodel client" error, with http code 404.
So, I'm trying to modify my web.config file, but I get only different errors. For example, now I have try to add a SOAP endpoint,but I get a "bad request" error.
This is one of my methods (they are defined in the same way)
[OperationContract]
[WebGet(UriTemplate = "impianto.json?retista={codret}&storeID={storeID}&H={hashedString}", ResponseFormat = WebMessageFormat.Json)]
List<WrapImpianti> GetImpiantoJSON(string codret, string storeID, string hashedString);
and this is the web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
<add key="ServerAddress" value="37.59.146.241:8099/isOverviewExport.svc" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<services>
<service name="isOverviewExport.Service1" behaviorConfiguration="MyBehavior">
<endpoint address="soap" behaviorConfiguration="soapBehavior" binding="basicHttpBinding" name="s" contract="isOverviewExport.isOverviewExport"/>
<endpoint address="rest" behaviorConfiguration="restBehavior" binding="webHttpBinding" name="base" contract="isOverviewExport.isOverviewExport">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="SecurityByTransport" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
</binding>
</webHttpBinding>
</bindings>
<extensions>
<behaviorExtensions>
<add name="CorsSupport" type="WebHttpCors.CorsSupportBehaviorElement, WebHttpCors, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
<behaviors>
<endpointBehaviors>
<behavior name="restBehavior">
<!--<enableWebScript/>-->
<webHttp helpEnabled="true" />
<CorsSupport />
</behavior>
<behavior name="soapBehavior">
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MyBehavior">>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer ignoreExtensionDataObject="true" maxItemsInObjectGraph="123456" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
</system.serviceModel>
<system.webServer>
<directoryBrowse enabled="true" />
</system.webServer>
<connectionStrings>
<add name="Entities" connectionString="metadata=res://*/AccessData.Model.csdl|res://*/AccessData.Model.ssdl|res://*/AccessData.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=myds;initial catalog=mydb;persist security info=True;user id=myuser;password=mypwd;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
You can also try yourself adding the service reference (the link is the same as above, http://37.59.146.241:8097/isOverviewExport.svc ). Why the second line of this snippet gives me the error I wrote above?
var svc = new ServiceReference5.isOverviewExportClient();
var ret = svc.GetImpiantoXML("123456", "AAA111", "test");
So, how can I use it as service reference in VS? I was thinking I have to set the soap endpoint, but maybe it isn't correct. Can you help me? :)

"There was no endpoint listening" - Configuration Mismatch Perhaps?

I get
"There was no endpoint listening at https://localhost/BassCoastServices/GeneralUtilityService.svc that
could accept the message. This is often caused by an incorrect address
or SOAP action. See InnerException, if present, for more details."
when I call the GeneralUtilityService from the client side and
"There was no channel actively listening at 'https://laura-laptop/BassCoastServices/GeneralUtilityService.svc'.
This is often caused by an incorrect address URI. Ensure that the
address to which the message is sent matches an address on which a
service is listening."
shows up when I debug w3wp.
Is there some sort of tool I can use that will make sure a client and server config file line up?
If this is an easy fix, please see the below App and Web config files.
App.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="Username" value="sampleuser"/>
<add key="Password" value="samplepassword"/>
<add key="basePath" value="C:\Temp"/>
</appSettings>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<bindings>
<wsHttpBinding>
<binding name="standardBinding" closeTimeout="01:00:00" openTimeout="01:00:00" receiveTimeout="01:00:00" sendTimeout="01:00:00" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" allowCookies="true">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="163840" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<reliableSession ordered="true" inactivityTimeout="01:00:00" enabled="false"/>
<security mode="TransportWithMessageCredential" >
<transport clientCredentialType="Certificate" proxyCredentialType="None" />
<message clientCredentialType="UserName" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ClientCertificateBehavior">
<callbackDebug includeExceptionDetailInFaults="true"/>
<clientCredentials>
<clientCertificate findValue="localhost" x509FindType="FindByIssuerName" storeLocation="LocalMachine" storeName="My">
</clientCertificate>
</clientCredentials>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="https://localhost/BassCoastServices/GeneralUtilityService.svc" behaviorConfiguration="ClientCertificateBehavior" binding="wsHttpBinding" bindingConfiguration="standardBinding" contract="Adapt.WCF.IGeneralUtilityService" name="IGeneralUtilityServiceEndPoint">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</client>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
</configuration>
Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
<add key="DatabaseConnectionString" value="Data Source=(local)\SQL2014;Initial Catalog=XIVICProduction;User ID=sa;Password=sameplepassword;MultipleActiveResultSets=True"/>
<add key="LogFilePath" value="C:\inetpub\wwwroot\Xivic\BassCoastServices\Log\Log.txt"/>
<add key="AllowMissingExternalIDs" value="true"/>
<!--No need to change-->
<add key="LogFileTypeLevel" value="Error"/>
<add key="SqlServerDateTimeStyle" value="103"/>
<add key="DatabaseType" value="Sql"/>
<add key="EnforceSecurityAtBusinessRulesLayer" value="false"/>
<add key="DateComparisonInaccuracy" value="35000"/>
<add key="CacheAccessItemsAtBusinessLayer" value="true"/>
<add key="CacheRecordsAtDataLayer" value="true"/>
<add key="SesionTimeout" value="1440"/>
</appSettings>
<system.serviceModel>
<services>
<!-- ENDPOINTS -->
<service name="IGeneralUtilityServiceEndPoint" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="wsHttpBinding" contract="Adapt.WCF.IGeneralUtilityService" bindingConfiguration="wsHttpEndpointBinding"/>
</service>
</services>
<!-- BEHAVIOURS -->
<behaviors>
<serviceBehaviors>
<behavior name="UserNameBehaviour">
<serviceThrottling maxConcurrentCalls="2147483647" maxConcurrentInstances="2147483647" maxConcurrentSessions="2147483647" />
<serviceDebug includeExceptionDetailInFaults="True" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Adapt.WCF.Security.CustomUserNameValidator, Adapt.WCF" />
<serviceCertificate findValue="localhost" x509FindType="FindByIssuerName" storeLocation="LocalMachine" storeName="My">
</serviceCertificate>
</serviceCredentials>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</serviceBehaviors>
</behaviors>
<!-- BINDINGS -->
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpointBinding">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "C:\inetpub\wwwroot\Xivic\BassCoastServices\Log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
<!--startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup-->
</configuration>
Calling WCF
_Channel = GetProxy<IGeneralUtilityService>();
_Channel.BeginTransaction(transactionId);
_Channel.CommitTransaction(transactionId);
public static T GetProxy<T>()
{
var channelFactory = new ChannelFactory<T>(string.Format("{0}EndPoint", typeof(T).Name));
channelFactory.Credentials.UserName.UserName = ConfigurationSettings.AppSettings["Username"];
channelFactory.Credentials.UserName.Password = ConfigurationSettings.AppSettings["Password"];
var workflowProxy = channelFactory.CreateChannel();
return workflowProxy;
}
Thanks in advance!
Update: I don't know what I did but now I'm getting
"Content Type application/soap+xml; charset=utf-8 was not supported by service http://localhost/BassCoastServices/GeneralUtilityService.svc. The client and service bindings may be mismatched."
Your problem is the way you create your channel factory. Some how it can not get the correct EndpointConfigurationName.
I'm not quite familiar on how to use only the EndpointConfigurationName as parameter in Channel Factory but you can try it this way:
var channelFactory = new ChannelFactory<T>("*", new EndpointAddress("https://localhost/BassCoastServices/GeneralUtilityService.svc"));
Well I don't know what the problem was but for anyone looking for a solution to this problem here are my web and app config files:
Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<!--Please configure-->
<!--Laura Local-->
<add key="DatabaseConnectionString" value="Data Source=(local)\SQL2014;Initial Catalog=XIVICProduction;User ID=sa;Password=samplepassword;MultipleActiveResultSets=True"/>
<!--No need to change-->
<add key="LogFilePath" value="C:\Temp\Log\log.txt" />
<add key="LogFileTypeLevel" value="Information" />
<add key="SqlServerDateTimeStyle" value="103" />
<add key="DatabaseType" value="Sql" />
<add key="EnforceSecurityAtBusinessRulesLayer" value="false" />
<add key="DateComparisonInaccuracy" value="35000" />
<add key="CacheAccessItemsAtBusinessLayer" value="true" />
<add key="CacheRecordsAtDataLayer" value="true" />
<!--Email Configuration-->
<!--add key="EmailAlertHost" value=""[INSERT="" HOST="" ADDRESS=""]/>
<add key="EmailAlertUsername" value=""[INSERT="" USERNAME=""]/>
<add key="EmailAlertPassword" value=""[INSERT="" PASSWORD=""] />
<add key="EmailAlertReplyToAddress" value=[INSERT REPLY TO ADDRESS] />
<add key="EmailAlertToAddress" value=""/>
<add key="EmailAlertCCAddress" value=""/>
<add key="EmailAlertSubject" value="*WARNING* - A Fatal Error Occurred # {0} - *WARNING*"/>
<add key="EmailAlertPriority" value="High"/-->
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
<system.web>
<compilation debug="true"/>
</system.web>
<system.serviceModel>
<services>
<!--AssetInventoryService-->
<service name="Adapt.WCF.AssetInventory.AssetInventoryService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.AssetInventory.AssetInventoryService" bindingConfiguration="UserNameBinding" />
</service>
<!--AssetValuationUtilityService-->
<service name="Adapt.WCF.AssetValuation.AssetValuationUtilityService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.IAssetValuationUtilityService" bindingConfiguration="UserNameBinding" />
</service>
<!--CodeGenerationService-->
<service name="Adapt.WCF.CodeGeneration.CodeGenerationService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.CodeGeneration.CodeGenerationService" bindingConfiguration="UserNameBinding" />
</service>
<!--CodeUtilityService-->
<service name="Adapt.WCF.CodeGeneration.CodeUtilityService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.CodeGeneration.ICodeUtilityService" bindingConfiguration="UserNameBinding"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8731/CodeUtilityService.svc" />
</baseAddresses>
</host>
</service>
<!--DataSchemaService-->
<service name="Adapt.WCF.DataSchema.DataSchemaService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.DataSchema.DataSchemaService" bindingConfiguration="UserNameBinding" />
</service>
<!--DataTransactionService-->
<service name="Adapt.WCF.DataTransaction.DataTransactionService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.DataTransaction.DataTransactionService" bindingConfiguration="UserNameBinding" />
</service>
<!--GeneralUtilityService-->
<service name="Adapt.WCF.GeneralUtilityService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.IGeneralUtilityService" bindingConfiguration="UserNameBinding"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8731/GeneralUtilityService.svc" />
</baseAddresses>
</host>
</service>
<!--SecurityService-->
<service name="Adapt.WCF.Security.SecurityService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.Security.SecurityService" bindingConfiguration="UserNameBinding" />
</service>
<!--SyncService-->
<service name="Adapt.WCF.SyncService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.ISyncService" bindingConfiguration="UserNameBinding" />
</service>
<!--SystemSetupService-->
<service name="Adapt.WCF.SystemSetup.SystemSetupService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.SystemSetup.SystemSetupService" bindingConfiguration="UserNameBinding" />
</service>
<!--TaskManagementService-->
<service name="Adapt.WCF.TaskManagement.TaskManagementService" behaviorConfiguration="UserNameBehaviour">
<endpoint binding="customBinding" contract="Adapt.WCF.TaskManagement.TaskManagementService" bindingConfiguration="UserNameBinding" />
</service>
</services>
<!-- BEHAVIOURS -->
<behaviors>
<serviceBehaviors>
<behavior name="UserNameBehaviour">
<serviceThrottling maxConcurrentCalls="2147483647" maxConcurrentInstances="2147483647" maxConcurrentSessions="2147483647" />
<serviceDebug includeExceptionDetailInFaults="True" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Adapt.WCF.Security.CustomUserNameValidator, Adapt.WCF" />
<serviceCertificate findValue="localhost" x509FindType="FindByIssuerName" storeLocation="LocalMachine" storeName="My">
</serviceCertificate>
</serviceCredentials>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</serviceBehaviors>
</behaviors>
<!-- BINDINGS -->
<bindings>
<customBinding>
<binding name="UserNameBinding" closeTimeout="23:00:00" openTimeout="23:00:00" receiveTimeout="23:00:00" sendTimeout="23:00:00">
<security authenticationMode="SecureConversation" requireSecurityContextCancellation="true">
<secureConversationBootstrap authenticationMode="UserNameForSslNegotiated">
</secureConversationBootstrap>
</security>
<textMessageEncoding>
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</textMessageEncoding>
<httpTransport transferMode="Buffered" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
</system.serviceModel>
<!--<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\temp\log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>-->
</configuration>
App.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="Username" value="dspec"/>
<add key="Password" value="samplepassword"/>
<add key="BasePath" value="c:\FileDrop"/>
</appSettings>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<bindings>
<wsHttpBinding>
<binding name="standardBinding" closeTimeout="01:00:00" openTimeout="01:00:00" receiveTimeout="01:00:00" sendTimeout="01:00:00" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" allowCookies="true">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="163840" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<reliableSession ordered="true" inactivityTimeout="01:00:00" enabled="false"/>
<security mode="Message">
<transport clientCredentialType="Certificate" proxyCredentialType="None" realm=""/>
<message clientCredentialType="UserName" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ClientCertificateBehavior">
<callbackDebug includeExceptionDetailInFaults="true"/>
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="None"/>
</serviceCertificate>
</clientCredentials>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost/BassCoastServices/GeneralUtilityService.svc" behaviorConfiguration="ClientCertificateBehavior" binding="wsHttpBinding" bindingConfiguration="standardBinding" contract="Adapt.WCF.IGeneralUtilityService" name="IGeneralUtilityServiceEndPoint">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</client>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
</configuration>

Named connection with Entity Framework via WCF not found?

I'm new trying to build an N-tier app through WCF and Entity Framework. I'm new to all of these, so apologies if I sound ignorant.
I'm attempting to test, and I get this error when I attempt to query the database through my WCF service.
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
I just copy-pasted my connection string from the Entity Framework project to my WCF host web.config, so I'm not sure what's wrong.
Any ideas?
web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="AerosPACE_CCADEEntities" connectionString="metadata=res://*/AerospaceModel.csdl|res://*/AerospaceModel.ssdl|res://*/AerospaceModel.msl;provider=System.Data.SqlClient;provider connection string="data source=****;initial catalog=AerosPACE_CCADE;persist security info=True;user id=****;password=****;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="AerospaceCCADE.Server.Domain.Service.AerosPACE_CCADEDataService">
<endpoint address="" binding="wsHttpBinding" contract="AerospaceCCADE.Common.Domain.Service.Contracts.IAerosPACE_CCADEDataService" bindingConfiguration="WS-AT" />
<endpoint address="basic" binding="basicHttpBinding" contract="AerospaceCCADE.Common.Domain.Service.Contracts.IAerosPACE_CCADEDataService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="WS-AT" transactionFlow="true" />
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization impersonateCallerForAllOperations="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
And the client App.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
</connectionStrings>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_DataService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="true" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="67108864"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None" realm=""/>
<message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:5482/AerosPACE_CCADEDataService.svc"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_DataService"
contract="AerospaceCCADE.Common.Domain.Service.Contracts.IAerosPACE_CCADEDataService"
name="AerosPACE_CCADEDataService"/>
</client>
<behaviors>
<endpointBehaviors>
<behavior>
<clientCredentials>
<!--allow server to use client credentials for impersonation-->
<windows allowedImpersonationLevel="Impersonation" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
You also need the entityFramework section.
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>

Categories