I'm trying to get https working with basicHttpBinding in WCF. The service seems to run fine, but when I try to run my client and when it gets to calling one of the methods on the service, I get the following exception:
Could not establish trust relationship for the SSL/TLS secure channel with authority 'sfs-111:20023'.
I've included my code and config files below. If anyone could help, I'd be very grateful.
Please note, I'm new to WCF.
HERE'S MY SERVICE APP.CONFIG:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- DEBUG - TURN ON TRACING -->
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\tahseen\dd\WCFServer.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<!-- BEHAVIOR FOR META DATA -->
<behavior name="DeltaServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceCredentials>
<windowsAuthentication includeWindowsGroups="false" allowAnonymousLogons="false" />
</serviceCredentials>
<dataContractSerializer maxItemsInObjectGraph="100000000" />
</behavior>
<!-- BEHAVIOR FOR TRANSPORT SECURITY -->
<behavior name="SecureBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerTrust" />
</clientCertificate>
<serviceCertificate findValue="sfs-Test" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
</serviceCredentials>
<dataContractSerializer maxItemsInObjectGraph="100000000" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<!-- DEFINE BINDING -->
<basicHttpBinding>
<binding name="HttpBinding_AlphaSystem">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<!-- DEFINE SERVICE -->
<service behaviorConfiguration="SecureBehavior" name="Alpha.Services.DeltaService.DeltaService">
<!-- ENDPOINT FOR METADATA -->
<endpoint address="mex" binding="basicHttpBinding" bindingConfiguration="" contract="IMetadataExchange" />
<!-- ENDPOINT FOR DATA -->
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="HttpBinding_AlphaSystem" contract="Alpha.Services.DeltaService.IDeltaService"/>
<!-- BASE ADDRESSES FOR SERVICE-->
<host>
<baseAddresses>
<add baseAddress="http://SFS-111:20022/DeltaService" />
<add baseAddress="https://SFS-111:20023/DeltaService" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
HERE'S MY CLIENT APP.CONFIG:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\tahseen\dd\WCFClient.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
<system.serviceModel>
<!-- DEFINE SECURE BEHAVIOR -->
<behaviors>
<endpointBehaviors>
<behavior name="ClientBehavior">
<clientCredentials>
<clientCertificate findValue="sfs-Client" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
<serviceCertificate>
<authentication certificateValidationMode="PeerTrust"/>
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IDeltaService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Certificate" realm="" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://sfs-111:20023/DeltaService" binding="basicHttpBinding" behaviorConfiguration ="ClientBehavior"
bindingConfiguration="BasicHttpBinding_IDeltaService" contract="DeltaService.IDeltaService"
name="BasicHttpBinding_IDeltaService">
<identity>
<dns value="sfs-Test" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
HERE'S MY SERVICE CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Alpha.Services.DeltaService
{
public class DeltaService : IDeltaService
{
public int timesTwo(int n)
{
return n * 2;
}
}
[ServiceContract]
interface IDeltaService
{
[OperationContract]
int timesTwo(int n);
}
public class App
{
public static void Main(string[] args)
{
//DeltaService service = new DeltaService();
ServiceHost serviceHost = new ServiceHost(typeof(DeltaService));
serviceHost.Open();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
serviceHost.Close();
}
}
}
HERE'S MY CLIENT CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WCFClient
{
class Program
{
static void Main(string[] args)
{
DeltaService.IDeltaService service = new DeltaService.DeltaServiceClient();
int result = service.timesTwo(5);
Console.WriteLine(result);
}
}
}
just for testing, try to disable ssl validation on the client:
http://webservices20.blogspot.com/2008/12/wcf-gotcha-disabling-ssl-validation.html
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
...
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidationCallback);
...
public static bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
Related
I made a WCF with one void method and deployed it on IIS; it works fine (the service response is code 202) until I put it under SSL with Client Certificate Authentication: in this case the code behind the operation is not executed and the server response is 200. No Exception seems to be raised (No Failed Request is traced, no Errors on Events Viewer) but I can't get the execution of called method
Here's the WCF implementation and configuration:
namespace WcfTestService
{
[ServiceContract]
public interface IWcfTestService
{
[OperationContract(IsOneWay =true)]
void OneWay(int value);
}
[ServiceBehavior]
public class Service1 : IWcfTestService
{
[OperationBehavior]
public void OneWay(int value)
{
Trace.TraceInformation(DateTime.Now.ToString() + " Oneway method invoked!" );
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="WcfTestBinding" messageEncoding="Text" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="50000000" maxReceivedMessageSize="50000000">
<readerQuotas maxDepth="500000000" maxStringContentLength="500000000" maxArrayLength="500000000" maxBytesPerRead="500000000" maxNameTableCharCount="500000000" />
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="WcfTestService.Service1" behaviorConfiguration="WcfTestBehaviors">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="WcfTestBinding" contract="WcfTestService.IWcfTestService" />
<endpoint contract="IMetadataExchange" binding="mexHttpsBinding" address="mex" />
</service>
</services>
<protocolMapping>
<add binding="wsHttpBinding" scheme="https" />
</protocolMapping>
<behaviors>
<serviceBehaviors>
<behavior name="WcfTestBehaviors">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances="500" maxConcurrentSessions="500" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
<security>
<authentication>
<anonymousAuthentication enabled="true" />
<iisClientCertificateMappingAuthentication enabled="true">
<oneToOneMappings>
<clear />
</oneToOneMappings>
</iisClientCertificateMappingAuthentication>
</authentication>
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" users="" roles="Users" />
</authorization>
</security>
<tracing>
<traceFailedRequests>
<remove path="*" />
<add path="*">
<traceAreas>
<add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI" verbosity="Verbose" />
</traceAreas>
<failureDefinitions timeTaken="00:00:00" statusCodes="401.2,202" />
</add>
</traceFailedRequests>
</tracing>
</system.webServer>
<system.diagnostics>
<switches>
<add name="DataMessagesSwitch" value="1" />
<add name="TraceLevelSwitch" value="4" />
</switches>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="WcfTestServiceTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="logs\WcfTestService.txt" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
The client code and its configuration:
static bool Test()
{
string certPath = #"C:\myCertName.pfx";
string pwdValue = "myPassword";
bool res = false;
EndpointAddress newEP = new EndpointAddress("https://myservername/WcfTestService");
BasicHttpsBinding newBind = new BasicHttpsBinding();
newBind.Security.Mode = BasicHttpsSecurityMode.Transport;
newBind.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
srvRefTest.WcfTestServiceClient myWS = new srvRefTest.WcfTestServiceClient(newBind,newEP);
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
X509Certificate2 ccert = new X509Certificate2(certPath, pwdValue);
myWS.ClientCredentials.ClientCertificate.Certificate = ccert;
myWS.OneWay(1);
return res;
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IWcfTestService">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://myservername/WcfTestService/WcfTestService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IWcfTestService"
contract="srvRefTest.IWcfTestService" name="BasicHttpBinding_IWcfTestService" />
</client>
</system.serviceModel>
</configuration>
On server logs I can see this call:
2019-01-11 14:45:01 W3SVC1 10.0.0.4 POST /WcfTestService - 443 SDI_user 130.0.139.146 - 200 0 0 187
where SDI_user is the name of the user specified in the section of manyToOneMapping in IIS as shown in picture:
(https://drive.google.com/open?id=1gGN6HrIDC9u160FuWx6MBwgi7MW7ppRS)
the best thing to do is to add WCF tracing both on the server and in the client side
https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/configuring-tracing
this should give you details of what is happening. If needed post here the svclog file
I reviewed your configuration and wanted to know why not using client certificate in a standard way - didn't understand security mode - transport doing both transport and message security
I suggest you follow the example from: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/transport-security-with-certificate-authentication
Use wsHttpBinding look here for comparison: https://www.codeproject.com/Articles/36396/Difference-between-BasicHttpBinding-and-WsHttpBind
thanks to everyone (expecially oshvartz); I just found the cause: in the client code I had to specify the endpoint address complete of .svc file. Here's the full code and configuration.
WCF implementation and configuration:
namespace WcfTestService
{
[ServiceContract]
public interface IWcfTestService
{
[OperationContract(IsOneWay =true)]
[XmlSerializerFormat()]
void OneWay(int value);
}
}
namespace WcfTestService
{
[ServiceBehavior]
public class Service1 : IWcfTestService
{
[OperationBehavior]
public void OneWay(int value)
{
Trace.TraceInformation(DateTime.Now.ToString() + " " + "Oneway method invoked! Parameter= " + value.ToString());
Trace.Flush();
}
}
}
WCF Configuration:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WcfTestBinding" messageEncoding="Mtom" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="50000000" maxReceivedMessageSize="50000000">
<readerQuotas maxDepth="500000000" maxStringContentLength="500000000" maxArrayLength="500000000" maxBytesPerRead="500000000" maxNameTableCharCount="500000000" />
<security mode="TransportWithMessageCredential">
<message clientCredentialType="Certificate" />
<transport clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="WcfTestService.Service1" behaviorConfiguration="WcfTestBehaviors">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="WcfTestBinding" contract="WcfTestService.IWcfTestService" />
<endpoint contract="IMetadataExchange" binding="mexHttpsBinding" address="mex" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfTestBehaviors">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
<security>
<authentication>
<anonymousAuthentication enabled="true" />
</authentication>
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" users="myuser" />
</authorization>
</security>
<tracing>
<traceFailedRequests>
<remove path="*" />
<add path="*">
<traceAreas>
<add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI" verbosity="Verbose" />
</traceAreas>
<failureDefinitions timeTaken="00:00:00" statusCodes="401-500" />
</add>
</traceFailedRequests>
</tracing>
</system.webServer>
<system.diagnostics>
<switches>
<add name="DataMessagesSwitch" value="1" />
<add name="TraceLevelSwitch" value="4" />
</switches>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="WCFConsumerTraceListener" type="System.Diagnostics.TextWriterTraceListener"
initializeData="logs\WcfTestService.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
Client implementation:
static void Test1Remoto()
{
EndpointAddress newEP = new EndpointAddress("https://mydomain/WcfTestService/WcfTestService.svc");
BasicHttpsBinding newBind = new BasicHttpsBinding();
newBind.Security.Mode = BasicHttpsSecurityMode.Transport;
newBind.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
srvRefTest.WcfTestServiceClient myWS = new srvRefTest.WcfTestServiceClient(newBind,newEP);
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
X509Certificate2 ccert = new X509Certificate2(certPath, pwdValue);
myWS.ClientCredentials.ClientCertificate.Certificate = ccert;
myWS.OneWay(1);
myWS.Close();
}
Client configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IWcfTestService" messageEncoding="Mtom">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" />
<message clientCredentialType="Windows" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://mydomain/WcfTestService/WcfTestService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IWcfTestService"
contract="srvRefTest.IWcfTestService" name="WSHttpBinding_IWcfTestService" />
</client>
</system.serviceModel>
</configuration>
I am trying to set up a WCF webservice with BasicHttpBinding and authentication using username/password. I made custom authentication class. However, it is never called (verified by debugging). This is my web.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
<serviceBehaviors>
<behavior>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Compareware_WebApp.webservices.AuthenticationValidator, Compareware_WebApp" />
</serviceCredentials>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding">
<security mode="TransportCredentialOnly">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Compareware_WebApp.webservices.Accounts">
<endpoint address="/webservices/Accounts.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding" name="BasicEndpoint"
contract="Compareware_WebApp.webservices.IAccounts" />
</service>
</services>
<client />
This is my authentication class:
namespace Compareware_WebApp.webservices
{
public class AuthenticationValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException();
}
if (!Membership.ValidateUser(userName, password))
{
// This throws an informative fault to the client.
throw new FaultException("Unknown Username or Incorrect Password");
}
}
}
}
What am I doing wrong?
I also stuck in this problem, And I got the solutions. If you want to call the Validate method of the UserNamePasswordValidator So, you must be have to use the TransportWithMessageCredential security.
NOTE: You must be have to host the WCF Services at the IIS server and have to enable the SSL for you website otherwise it will be not work. If we use the TransportWithMessageCredential than we have to enable the SSL for the our website.
WCF Server Web.config file
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttp">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="TransportWithMessageCredential.Service1" behaviorConfiguration="wsHttpBehavior">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttp" contract="TransportWithMessageCredential.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<host>
<baseAddresses>
<add baseAddress="https://localhost:8080/WCFDemo"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="wsHttpBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="TransportWithMessageCredential.ServiceAuthanticator, TransportWithMessageCredential"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
Service Authentication class
public class ServiceAuthanticator : UserNamePasswordValidator
{
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
public override void Validate(string userName, string password)
{
if (String.IsNullOrEmpty(userName) || String.IsNullOrEmpty(password))
{
throw new FaultException("Please, Provide the username and password!!!");
}
if (userName != "abc" || password != "abc")
{
throw new FaultException("Sorry, Invalid username or password!!!");
}
}
}
WCF Client app.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IService1">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://kalpesh-pc/WCFAuth/Service1.svc" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"
name="WSHttpBinding_IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
Client Program to call the WCF Services
try
{
Service1Client objClient = new Service1Client();
objClient.ClientCredentials.UserName.UserName = "abc";
objClient.ClientCredentials.UserName.Password = "abc";
objClient.Open();
string strData = objClient.GetData(10);
}
catch (FaultException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
Happy Coding...
:)
Transport, as far as I understand, requires HTTPS to encrypt credentials and throws an exception if there is no SSL. TransportCredentialOnly will send the credentials in plain text and unencrypted and is recommended for testing ONLY.
Therefore, your credentials are send via transport. So <Transport> tag must be adjusted, not <Message>.
The following works for me:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic"/>
</security>
Hi I am having an WCF sync Service hosting on IIS7 on my server, I can access the URL in browser, Actually i built the WCF service and later on i added a wcf service website to my solution by adding my wcf service reference. and in the service.svc file i mentioned the particular service. the web.config in the wcf site looks like
<configuration>
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="SimGuru_WCF.SimGuruDBCacheSyncService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
contract="SimGuru_WCF.ISimGuruDBCacheSyncContract">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
When i am trying to access the service it is giving me the "The remote server returned an error: (404) Not found" but still i can access the service through URL
And app.config file is
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="SimGuru_WCF.Properties.Settings.ServerSimGuru_RetailConnectionString"
connectionString="Data Source=SIMGURU\SQLEXPRESS;Initial Catalog=SimGuru_Retail;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISimGuruDBCacheSyncContract" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="SimGuru_WCF.SimGuruDBCacheSyncServiceBehavior"
name="SimGuru_WCF.SimGuruDBCacheSyncService">
<endpoint address="" binding="basicHttpBinding" contract="SimGuru_WCF.ISimGuruDBCacheSyncContract">
<identity>
<dns value="10.0.1.42"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://10.0.1.42:8731/SimGuruDBCacheSyncService/" />
</baseAddresses>
<timeouts closeTimeout="00:01:10" openTimeout="00:09:00" />
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SimGuru_WCF.SimGuruDBCacheSyncServiceBehavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>
can some one please help me to sort this issue out
Thanks in advance
I got it, using trace i was able to sort my problem
<diagnostics>
<messageLogging maxMessagesToLog="30000"
logEntireMessage="true"
logMessagesAtServiceLevel="true"
logMalformedMessages="true"
logMessagesAtTransportLevel="true">
</messageLogging>
</diagnostics>
</system.serviceModel>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Verbose, ActivityTracing"
propagateActivity="true" >
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging"
switchValue="Verbose">
<listeners>
<add name="xml" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="e2eTraceTest.e2e" />
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
The Trace viewer explained me where i am doing wrong one thing is that security issues with the sql server, and more over i don't even have a connection string property in my web. config file i have one on wcf service but not on wcf web site
Any how it is solved
thanks all for your co-operation
We are getting following exception in the .svclog file generated through system diagnostics config settings at server side.
Exception: System.ServiceModel.ProtocolException
Message: The number of bytes available is inconsistent with the HTTP Content-Length
header. There may have been a network error or the client may be
sending invalid requests.
We have observed that the data sent by WCF client is broken. We came to know about this by viewing the message xml in the .svclog file generated at WCF client side.
Actually we are sending data large data by dividing it into small chunks calling the WCF service method to send data in a loop. Following is the code for the same at WCF client side.
DataTable dtStockDetails = new DataTable("StockDetails");
sqlDataAdapter.Fill(dtStockDetails);
int stockDetailsBatchSize = 100;
DataTable dtStockDetailsBatch = dtStockDetails.Clone();
DataRow dr;
int stockDetailsBatchCount = 0;
int stockDetailsTotalRecords = dtStockDetails.Rows.Count;
while (dtStockDetails.Rows.Count > 0)
{
dr = dtStockDetails.Rows[0];
dtStockDetailsBatch.ImportRow(dr);
dtStockDetailsBatch.AcceptChanges();
dtStockDetails.Rows.Remove(dr);
dtStockDetails.AcceptChanges();
if ((dtStockDetailsBatch.Rows.Count == stockDetailsBatchSize) || (dtStockDetails.Rows.Count == 0))
{
stockDetailsBatchCount++;
sendStockDetailsResult = serviceClient.SendStockDetails(dtStockDetailsBatch);
dtStockDetailsBatch.Clear();
}
}
Now WCF client some times sends 7 batches of data, some times sends 9 batches of data, some times sends 10 batches of data, .... . In all cases lase message(data batch) xml gets corrupted. This behavior is random.
We are not sure why the message xml is getting corrupted and resulting into end of communication. It never sends all batches of data.
Following are config settings:
WCF Service config settings:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="InventoryServices.InventoryImportServiceBehavior"
name="InventoryServices.InventoryImportService">
<endpoint address="https://www.domain.com/InventoryServices/InventoryImportService.svc" behaviorConfiguration="wsServiceEndpointBehavior"
binding="wsHttpBinding" bindingConfiguration="b1" contract="InventoryServices.IInventoryImportService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://www.domain.com" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="b1" closeTimeout="00:30:00" openTimeout="00:30:00"
receiveTimeout="00:30:00" sendTimeout="00:30:00" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<reliableSession inactivityTimeout="00:30:00" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Certificate">
</transport>
<message clientCredentialType="UserName" negotiateServiceCredential="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="wsServiceEndpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="InventoryServices.InventoryImportServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<serviceCertificate findValue="XyzClient" x509FindType="FindBySubjectName" />
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="InventoryServices.Helpers.CustomValidator, InventoryServices" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
WCF Client config settings:
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
maxSizeOfMessageToLog="2147483647" />
</diagnostics>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IInventoryImportService"
closeTimeout="00:30:00" openTimeout="00:30:00" receiveTimeout="00:30:00"
sendTimeout="00:30:00" bypassProxyOnLocal="false" transactionFlow="false"
hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" 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:30:00"
enabled="false" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="">
<extendedProtectionPolicy policyEnforcement="Never" />
</transport>
<message clientCredentialType="UserName" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://www.domain.com/InventoryServices/InventoryImportService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IInventoryImportService"
contract="InventoryImportService.IInventoryImportService"
name="WSHttpBinding_IInventoryImportService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
</system.serviceModel>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Verbose, ActivityTracing"
propagateActivity="false">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="sharedListener">
<filter type="" />
</add>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="sharedListener">
<filter type="" />
</add>
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\Program Files\InventoryExportUtilitySetup\servicetrace.svclog"
type="System.Diagnostics.XmlWriterTraceListener" name="sharedListener">
<filter type="" />
</add>
</sharedListeners>
</system.diagnostics>
Can any one please suggest what should we do to resolve this problem?
Thanks in advance.
Looking at your configuration the Reader Quotas settings on Server and Client are different.
Make sure you have large values mostly same on client and server.
Just wanted to know if you have tried sending in any small payload data to make sure that the service is working fine?
I also noticed that you have your security set to "TransportWithMessageCredential" and you have the mex endpoint with mexHttpBinding. I guess that should have been mexHttpsBinding and also your httpGetEnabled attribute is set to true where as it should have been httpsGetEnabled to true.
I have created a WCF REST Service and have successfully created a function to upload a file from the client to the service.
The problem is, this only works when the file being sent is 64kb or less. How can I fix this problem.
web.config file:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="100000000"> </requestLimits>
</requestFiltering>
</security>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
and global.asax:
namespace WCFRESTService
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("RO", new WebServiceHostFactory(), typeof(Service1)));
}
}
}
After 3 days of my googling search finally i found the solution
In my solution, web.config i've added https code and etc. after that i have removed all the config and added this below code
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehaviour" name="NativeAppServices.Service1">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="StreamedRequestWebBinding" contract="NativeAppServices.IService1" behaviorConfiguration="webBehavior">
</endpoint>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="StreamedRequestWebBinding" closeTimeout="00:25:00"
openTimeout="00:25:00" receiveTimeout="00:25:00" sendTimeout="00:25:00"
bypassProxyOnLocal="true" hostNameComparisonMode="WeakWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
transferMode="StreamedRequest" useDefaultWebProxy="false">
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors >
<behavior name="ServiceBehaviour">
<!-- 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"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"></serviceHostingEnvironment>
</system.serviceModel>
<system.webServer>
<directoryBrowse enabled="true"/>
</system.webServer>
Figured it out. Had to add attributes "maxReceivedMessageSize" and "maxBufferSize" to the