system.service.security error when using wshttp binding - c#

i am getting the following error when i try access my webservice from the client application which is a windows based app
System.ServiceModel.Security.SecurityNegotiationException:
Secure channel cannot be opened
because security negotiation with the
remote endpoint has failed. This may
be due to absent or incorrectly
specified EndpointIdentity in the
EndpointAddress used to create the
channel. Please verify the
EndpointIdentity specified or implied
by the EndpointAddress correctly
identifies the remote endpoint. --->
System.ServiceModel.FaultException:
The request for security token has
invalid or malformed elements. at
System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message
message, EndpointAddress target) at
System.ServiceModel.Security.IssuanceTokenProviderBase`1.ThrowIfFault(Message
message, EndpointAddress target) at
System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message
incomingMessage,
SspiNegotiationTokenProviderState
sspiState) --- End of inner
exception stack trace ---
Server stack trace: at
System.ServiceModel.Security.IssuanceTokenProviderBase1.DoNegotiation(TimeSpan
timeout) at
System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Security.TlsnegoTokenProvider.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Security.SecurityUtils.OpenCommunicationObject(ICommunicationObject
obj, TimeSpan timeout) at
System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Channels.SecurityChannelFactory1.ClientSecurityChannel1.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation
operation, EndpointAddress target, Uri
via, SecurityToken currentToken,
TimeSpan timeout) at
System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan
timeout) at
System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan
timeout) at
System.ServiceModel.Security.SecuritySessionClientSettings1.ClientSecuritySessionChannel.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan
timeout, CallOnceManager cascade)
at
System.ServiceModel.Channels.ServiceChannel.EnsureOpened(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)
i am also using asp membership provider....
i have been trying to get this working for the last couple hours but i'm getting nowhere..... the funny thing is that the app works on the local machine but not from a remote machine
thanks
{
<services>
<service name="AutoWatch.Entity.WcfService.SecurityService" behaviorConfiguration="ServiceBehavior">
<endpoint binding="wsHttpBinding" bindingConfiguration="ServiceBinding" bindingName="ServiceBinding" contract="AutoWatch.Entity.WcfService.ISecurityService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost..." />
</baseAddresses>
</host>
</service>
<service name="servicename" behaviorConfiguration="ServiceBehavior">
<endpoint binding="wsHttpBinding" bindingConfiguration="ServiceBinding" bindingName="ServiceBinding" contract="Service" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost/.../" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="ServiceBinding"></binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- Configure role based authorization to use the Role Provider -->
<serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="SqlRoleProvider" />
<serviceCredentials>
<!-- Configure user name authentication to use the Membership Provider -->
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="SqlMembershipProvider" />
<!-- Configure the service certificate -->
<serviceCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" findValue="......co.za" />
</serviceCredentials>
<!-- 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="True" />
</behavior>
</serviceBehaviors>
</behaviors>
}

Related

WCF service with certificate authentication: "The caller was not authenticated by the service"

I'm trying to setup a WCF service with certificate-based authentication, following this guide: https://msdn.microsoft.com/en-au/library/ff648360.aspx?f=255&MSPPError=-2147217396
I've followed all the steps (I think), which in summary are:
1) Generated a self-signed CA certificate and installed it as a machine-level trusted CA:
2) Generated a certificate for the service (signed by the CA certificate, CN=QvxServiceCert) and installed it at machine-level:
3) configured the WCF service endpoint behavior to use the certificate. My service configuration looks like this:
<?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="wsHttpEndpointBinding">
<security>
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="QvxServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<serviceCertificate findValue="CN=QvxServiceCert" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="esqQvxScheduler.Service.QvxSchedulerAPI" behaviorConfiguration="QvxServiceBehavior">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding"
name="wsHttpEndpoint" bindingName="" contract="esqQvxScheduler.Service.IQvxSchedulerAPI" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/QvxSchedulerAPI/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
4) Generated a certificate for the client (again, signed by the CA certificate, this one has CN=QvxClientCert) and installed at user-level:
5) configured the WCF client behavior to use it for authentication. This is my client config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="qvxClientBehavior">
<clientCredentials>
<clientCertificate findValue="CN=QvxClientCert" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpoint">
<security>
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8733/QvxSchedulerAPI/" binding="wsHttpBinding" behaviorConfiguration="qvxClientBehavior"
bindingConfiguration="wsHttpEndpoint" contract="QvxSchedulerAPI.IQvxSchedulerAPI"
name="wsHttpEndpoint">
<identity>
<certificate encodedValue="[A LONG AUTOGENERATED STRING THE MEANING OF WHICH I HAVE NO IDEA]" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
6) Gave the user that runs the client access to the certificate, by issuing the following on the command line: cacls "C:\Users\MyUsername\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-742627442-1779984360-2302642487-1000" /E /G "MyUser-PC\MyUsername":R
This was all done following the guide, without any issue that I could see. Everything seems ok... but when I try to invoke the service from my client, all I get this frustratingly vague and unhelpful exception:
Unhandled Exception: System.ServiceModel.Security.SecurityNegotiationException: The caller was not authenticated by the service. ---> System.ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed.
at System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message message, EndpointAddress target)
at System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message incomingMessage, SspiNegotiationTokenProviderState sspiState)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
at System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan timeout)
at System.ServiceModel.Security.TlsnegoTokenProvider.OnOpen(TimeSpan timeout)
at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Security.CommunicationObjectSecurityTokenProvider.Open(TimeSpan timeout)
at System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan timeout)
at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.ClientSecurityChannel`1.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan timeout)
at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
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)
Well, after a lot of trial and error, turns out that you either have to have a CRL installed for your CA or you have to specify explicitly that you don't want a revocation check, by adding this to your behavior's ClientCredentials tag:
<serviceCertificate>
<authentication revocationMode="NoCheck"/>
</serviceCertificate>
and vice-versa for the service side:
<clientCertificate>
<authentication certificateValidationMode="ChainTrust" revocationMode="NoCheck"/>
</clientCertificate>
Also, you need to remove the autogenerated certificate tag in the client and replace it with an instruction to look up the certificate:
<identity>
<certificateReference findValue="CN=QvxServiceCert" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
</identity>

The HTTP request was forbidden with client authentication scheme 'Anonymous' when access through a webhosted service

I am getting the following issue when i m trying to access the wcf service through WcfTestClient. The service is hosted on an Hostgator site
The HTTP request was forbidden with client authentication scheme 'Anonymous'.
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 INotifyService.saveNotifyEmail(NotifyBE notifyEntity)
at NotifyServiceClient.saveNotifyEmail(NotifyBE notifyEntity)
Inner Exception:
The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
Config file:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="WeddingNirvana.DataAccess" value="WeddingNirvana.DataAccess"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<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"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBindingConfig">
<security mode="None">
</security>
</binding>
</basicHttpBinding>
</bindings>
<protocolMapping>
<add binding="basicHttpBinding" scheme="http" bindingConfiguration="basicHttpBindingConfig" />
</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>
Could anyone help me with what the issue is.
I have tried using the answers that were already in stackoverflow but all of them are related to the Certificate, which i have not applied

There Was No Endpoint Listening at http // That Could Accept The Message in WCF

I am trying to develop a webservice. In my application I need to connect to my webservice without any referencing, so I use this code:
static void Main(string[] args)
{
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress("http://confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc");
ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
IService1 channel = factory.CreateChannel();
Console.WriteLine(channel.GetCategoryName(1));
Console.ReadLine();
}
But in this line channel.GetCategoryName(1) I get this error :
There was no endpoint listening at http://confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Here is my service webconfig:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<customErrors mode="Off"/>
<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>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
<services>
<service name="WcfServiceLibrary1.Service1">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary1/Service1/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc" binding="basicHttpBinding" contract="WcfServiceLibrary1.IService1">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<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" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
note:when I add the reference it works, it doesn't work when I don't add that to reference .
The error stacktrace:
System.ServiceModel.EndpointNotFoundException was unhandled by user code
HResult=-2146233087
Message=There was no endpoint listening at http://confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
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 WcfServiceLibrary1.IService1.GetCategoryName(Int32 productID)
at WebApplication1.WebForm1.Page_Load(Object sender, EventArgs e) in c:\Users\ehsan\Documents\Visual Studio 2012\Projects\WcfService1\WebApplication1\WebForm1.aspx.cs:line 20
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException: System.Net.WebException
HResult=-2146233079
Message=The remote server returned an error: (404) Not Found.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
InnerException
You said it worked when you added references. So my guess is that you have an issue in your endpoint.
According to your code you are expecting the endpoint to be http://confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc. But your actual endpoint is http://confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc/confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc.
In your wsdl it shows the url as
<wsdl:service name="Service1">
<wsdl:port name="BasicHttpBinding_IService1" binding="tns:BasicHttpBinding_IService1">
<soap:address location="http://confdemo.spadsystem.com
/WcfServiceLibrary1.Service1.svc/confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc"/>
</wsdl:port>
</wsdl:service>
I think this part this your web.config is not correct.
<endpoint address="confdemo.spadsystem.com/WcfServiceLibrary1.Service1.svc" binding="basicHttpBinding" contract="WcfServiceLibrary1.IService1">

Not getting data from WCF Service

I Hosted WCf Service in IIS and made that as independent virtual directory. When I host this service I Can see the Methods of WCF from WCF test client but can't access the data..
Could you quickly suggest where I'm going wrong
below is my code:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MobServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
<services>
<service name="ClubConnect.MobService" behaviorConfiguration="MobServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="ClubConnect.IMobService"/>
<endpoint address="ws" name="webHttpBinding" binding="webHttpBinding" contract="ClubConnect.IMobService" behaviorConfiguration="WebBehavior" >
<identity>
<dns value="http://domain/mobile_app/mobservice.svc" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
Error:
The content type text/html; charset=UTF-8 of the response message does
not match the content type of the binding (application/soap+xml;
charset=utf-8). If using a custom encoder, be sure that the
IsContentTypeSupported method is implemented properly. The first 1024
bytes of the response were: ' '. Server stack trace: at
System.ServiceModel.Security.IssuanceTokenProviderBase1.DoNegotiation(TimeSpan
timeout) at
System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Security.CommunicationObjectSecurityTokenProvider.Open(TimeSpan
timeout) at
System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Channels.SecurityChannelFactory1.ClientSecurityChannel1.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation
operation, EndpointAddress target, Uri via, SecurityToken
currentToken, TimeSpan timeout) at
System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan
timeout) at
System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan
timeout) at
System.ServiceModel.Security.SecuritySessionClientSettings1.ClientSecuritySessionChannel.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel
channel, TimeSpan timeout) at
System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan
timeout, CallOnceManager cascade) 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 IMobService.GetCategoryList() at
MobServiceClient.GetCategoryList()

How to dynamically call a net.tcp Web Service

I am trying to call a WCF from my C# desktop app but i get an error. This is my code:
//Client Code
System.ServiceModel.EndpointAddress addressSync = new System.ServiceModel.EndpointAddress("net.tcp://an ip address/Sync2.svc");
Shared.FactorySync = new System.ServiceModel.ChannelFactory<LiteEdition.wsSyncFastest.ISync2Channel>("NetTcpBinding_ISync2", addressSync);
Shared.UpLoadSync = Shared.FactorySync.CreateChannel();
[QUESTION. If I dynamically create a client call to a WCF can I assume i do NOT need to include anything in th app.config file about the bindings?]
//error message on this line:
Shared.UpLoadSync.UploadMotionDynamic2(new byte[1]{0}, 0, 0);
//IS:
The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9349963'
.
//My Service:
public void UploadMotionDynamic2(byte[] jpegData, int status, int framePart)
{
DAL dal = new DAL();
try
{
if (jpegData != null)
{
LiveView2.SetNewFrame(status, framePart, jpegData);
}
}
catch (Exception ex)
{
email.SendError("Sync.UploadMotionDynamic:" + ex.ToString(), "");
}
}
//In my Web.Config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="NetTCPBehaviour">
<serviceTimeouts transactionTimeout="0.00:00:30" />
<serviceDebug includeExceptionDetailInFaults="false" />
<dataContractSerializer maxItemsInObjectGraph="65536" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="testme" behaviorConfiguration="NetTCPBehaviour">
<endpoint address="Sync2.svc" binding="netTcpBinding" contract="ISync" name="wsMotionUploader" bindingConfiguration="NetTCPBindingEndPoint">
<!--<security mode="None"></security>-->
</endpoint>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="NetTCPBindingEndPoint" receiveTimeout="00:15:00" sendTimeout="00:15:00" transferMode="Streamed" closeTimeout="00:02:00" openTimeout="00:02:00"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<readerQuotas maxArrayLength="32768" />
<security mode="None">
<transport clientCredentialType="None" protectionLevel="None" />
<message clientCredentialType="None" />
</security>
</binding>
</netTcpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Amended Code:
System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding();
System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("http:ip/Sync2");
System.ServiceModel.ChannelFactory<System.ServiceModel.Channels.IRequestChannel> factory =
new System.ServiceModel.ChannelFactory<System.ServiceModel.Channels.IRequestChannel>(binding, address);
var channel = factory.CreateChannel();
channel.Open();
UPDATED TO THIS:
System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding();
System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("net.tcp://ip/Sync2");
System.ServiceModel.ChannelFactory<WindowsFormsApplication2.ws.ISync2Channel> factory =
new System.ServiceModel.ChannelFactory<WindowsFormsApplication2.ws.ISync2Channel>(binding, address);
factory.Endpoint.Contract.SessionMode = System.ServiceModel.SessionMode.Allowed;
WindowsFormsApplication2.ws.ISync2Channel channel = factory.CreateChannel();
channel.Open();
But get this error 'Object reference not set to an instance of an object.'
on the .Open() method.
Also, the 'WindowsFormsApplication2.ws.ISync2Channel' is defined because I had already added a reference to the Service. If I had not what would I have
used instead?
///******************new settings:
Client code:
ws.Sync2Client wcf = new ws.Sync2Client("NetTcpBinding_ISync2");
wcf.UploadMotionDynamic2(new byte[1]{1},0,0);
Client App.Config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISync2" />
</basicHttpBinding>
<netTcpBinding>
<binding name="NetTcpBinding_ISync2" />
</netTcpBinding>
</bindings>
<client>
<endpoint address="http://ip/Sync2.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISync2"
contract="ws.ISync2" name="BasicHttpBinding_ISync2" />
<endpoint address="net.tcp://ip/Sync2.svc" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_ISync2" contract="ws.ISync2"
name="NetTcpBinding_ISync2">
<identity>
<servicePrincipalName value="host/ip" />
</identity>
</endpoint>
</client>
</system.serviceModel>
Server Web.Config
-->
The error I get is on this line:
wcf.UploadMotionDynamic2(new byte[1]{1},0,0);
The error is:
Object reference not set to an instance of an object.
the stack is:
Server stack trace:
at System.ServiceModel.Channels.SocketConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
at System.ServiceModel.Channels.BufferedConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
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 WindowsFormsApplication2.ws.ISync2.UploadMotionDynamic2(Byte[] jpegData, Int32 status, Int32 framePart)
at WindowsFormsApplication2.ws.Sync2Client.UploadMotionDynamic2(Byte[] jpegData, Int32 status, Int32 framePart) in m:\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Service References\ws\Reference.cs:line 81
at WindowsFormsApplication2.Form1.button1_Click(Object sender, EventArgs e) in m:\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Form1.cs:line 581
This all works when I use http binding though...
The port 780 is open on my server.
the Net.Tcp.Listener Adaptor is running
Enabled Protocols in IIS has net.tcp
Still no joy
It looks like your using the wrong constructor for your requirements.
When using the ChannelFactory(String, EndpointAddress) constructor, the first parameter stands for the name of your endpoint configuration (in your config file).
Using the ChannelFactory(Binding, EndpointAddress) constructor will fulfill your requirement of passing the configuration programmatically.
Use this constructor when you want to pass the binding and address information programmatically rather than using an application configuration file.
You can use the ChannelFactory class to call the wcf service, in this case you dont need to have endpoints and bindings in configuration file. Everything(endpoints, behaviors) you can create in the c# something like below code
var channelFactory = new ChannelFactory<IService>(new BasicHttpBinding(), "http://myurl:8080/ServiceFirst");
IService client = channelFactory.CreateChannel();
check out this link
http://msdn.microsoft.com/en-us/library/ms734681(v=vs.110).aspx

Categories

Resources