WCF Router - Not Routing - c#

I have a WCF Router in a console application that works well, but I need to host this in Azure. As a result I have been asked to make this as a web app so it can be hosted as an app service.
The Router that I have uses this as a config right now
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="System.ServiceModel.Routing.RoutingService">
<endpoint
binding="basicHttpBinding"
contract="System.ServiceModel.Routing.IRequestReplyRouter"
name="proposalRouter" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:54636/routingService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceDebug includeExceptionDetailInFaults="true" />
<routing filterTableName="proposalRoutingTableVersion"/>
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding
name="TestBinding"
allowCookies="True"
closeTimeout="00:04:00"
openTimeout="00:00:10"
receiveTimeout="00:05:00"
sendTimeout="00:05:00"
maxReceivedMessageSize="15728640">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<routing>
<namespaceTable>
<add prefix="xxx" namespace="xxxxx"/>
</namespaceTable>
<filters>
<filter name="version_0_9"
filterType="Custom"
filterData="0.9"
customType="RouterService.Asp.VersionFilter, RouterService.Asp"
/>
<filter name="version_1_0"
filterType="Custom"
filterData="1.0"
customType="RouterService.Asp.VersionFilter, RouterService.Asp"
/>
</filters>
<filterTables>
<filterTable name="proposalRoutingTableVersion">
<!--<add filterName="version_0_9" endpointName="version_0_9"/>
<add filterName="version_1_0" endpointName="version_1_0"/>
-->
<!-- Acts as the else clause-->
<!--
<add filterName="noVersion" endpointName="version_0_9"/>-->
<add filterName="version_0_9" endpointName="version_0_9" priority="1"/>
<add filterName="version_1_0" endpointName="version_1_0" priority="0"/>
</filterTable>
</filterTables>
</routing>
<client>
<endpoint address="http://localhost:63690/ProposalService_1_00.svc"
binding="basicHttpBinding"
contract="*"
name="version_1_0"/>
<!--<endpoint address="http://localhost:63690/ProposalService.svc"
binding="basicHttpBinding"
contract="*"
name="version_0_9"/>-->
<!--<endpoint address="http://localhost:63253/ProposalService.svc"
binding="basicHttpBinding"
contract="*"
name="version_0_9"/>-->
</client>
</system.serviceModel>
This drops into the version filter
public class VersionFilter : MessageFilter
{
private string _filterData;
private readonly XNamespace _xmlnsa = "xxxxxx";
public VersionFilter(string filterData)
{
_filterData = filterData;
}
public override bool Match(MessageBuffer buffer)
{
throw new NotImplementedException();
}
public override bool Match(Message message)
{
XDocument doc = XDocument.Parse(message.ToString());
var version = (from xml in doc.Descendants(_xmlnsa + "getProposal")
select xml.Attribute("version")).FirstOrDefault();
return _filterData == version.Value.ToString(); ;
}
}
And then gives the true or false response, then does not hit either of my WebService end points that I am trying to hit.
I have looked in a variety of places for answers on this, but everywhere I have looked show the same \ similar code to what I have in place.
Some suggestions talk about decorating my enums with [EnumMember], so went and added this to every enum. This didnt help.
I have changed from basic to wsHttpBinding, this also did not help, and then I got a 415 error.
I cannot see why \ how changing from a console app to an ASP.Net WCF Application, and an ASP.Net Web Application would cause this to stop working.
In the interested of not missing anything out that I am not seeing this is the response received.
<s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode
xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault
</faultcode>
<faultstring xml:lang="en-GB">An unexpected failure occurred. Applications should not attempt to handle this error. For diagnostic purposes, this English message is associated with the failure: 'Shouldn't allocate SessionChannels if session-less and impersonating'.</faultstring>
<detail>
<ExceptionDetail
xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<HelpLink i:nil="true"/>
<InnerException i:nil="true"/>
<Message>An unexpected failure occurred. Applications should not attempt to handle this error. For diagnostic purposes, this English message is associated with the failure: 'Shouldn't allocate SessionChannels if session-less and impersonating'.</Message>
<StackTrace> at System.Runtime.Fx.AssertAndThrow(String description)
at System.ServiceModel.Routing.RoutingChannelExtension.get_SessionChannels()
at System.ServiceModel.Routing.RoutingService.GetOrCreateClient[TContract](RoutingEndpointTrait endpointTrait, Boolean impersonating)
at System.ServiceModel.Routing.ProcessRequestAsyncResult`1.StartProcessing()
at System.ServiceModel.Routing.ProcessRequestAsyncResult`1..ctor(RoutingService service, Message message, AsyncCallback callback, Object state)
at System.ServiceModel.Routing.RoutingService.BeginProcessRequest[TContract](Message message, AsyncCallback callback, Object state)
at System.ServiceModel.Routing.RoutingService.System.ServiceModel.Routing.IRequestReplyRouter.BeginProcessRequest(Message message, AsyncCallback callback, Object state)
at AsyncInvokeBeginBeginProcessRequest(Object , Object[] , AsyncCallback , Object )
at System.ServiceModel.Dispatcher.AsyncMethodInvoker.InvokeBegin(Object instance, Object[] inputs, AsyncCallback callback, Object state)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace>
<Type>System.Runtime.Fx+InternalException</Type>
</ExceptionDetail>
</detail>
</s:Fault>
</s:Body>
</s:Envelope>
I have tried enabling log, but dont get as far as writing one so not sure what else to try or do.

So, it turns out that this line in the web.config file was the issue
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
removing this line as suggested here https://seroter.com/2010/09/19/lesson-learned-wcf-routing-service-and-the-basichttpbinding/ was the solution to the problem.

Related

WCF: There was no endpoint listening at, that could accept the message

I have WCF Service (JSON), and ASP.NET website that we add a service reference to that site connected to the wcf service.
when i test the service using POSTMAN and SOAPUI and also when i try the following code:
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = System.Text.Encoding.UTF8;
string result = client.UploadString("http://localhost:1122/Service.svc/GetInfo", string.Empty);
It works fine (note that all my service functions are POST).
But when i add the service to service reference an connect to the service and try to call the function GetInfo(), the following issue appears.
Exception Message
There was no endpoint listening at http://localhost:1122/Service.svc that could
accept the message. This is often caused by an incorrect address or SOAP action.
See InnerException, if present, for more details.
Inner Exception Message
The remote server returned an error: (404) Not Found.
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)
I think this issue is due to incorrect configuration on the config file for the webservice and website, so you can find below both config files:
Webservice Config File:
<system.serviceModel>
<services>
<service name="WCFService.Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="webHttpBinding" contract="WCFService.IService" name="WebHttp_IService"
bindingConfiguration="WebHttpBinding_IService" behaviorConfiguration="ServiceBehaviorEndpoint" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="WebHttpBinding_IService" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" openTimeout="00:20:00" receiveTimeout="00:20:00" closeTimeout="00:20:00" sendTimeout="00:20:00">
<readerQuotas maxDepth="200" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="2147483647" maxNameTableCharCount="16384" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="ServiceBehaviorEndpoint">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Website Config File:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService"/>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
</binding>
</webHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1122/Service.svc" bindingConfiguration="BasicHttpBinding_IService"
contract="WCFServices.IService" name="BasicHttpBinding_IService" binding="basicHttpBinding" />
</client>
</system.serviceModel>
Note that the Service Reference name in the Website is WCFService, and we try to host the service to the iis with public IP and open the firewall, but the same issue appears.
When we invoke the service which created with WebHttpBinding via client proxy class, there may be some differences from other bindings. We need to configure the client configuration manually, such as adding the endpoint behavior to service endpoint and webget/webinvoke attribute to the automatically generated operation method by adding service reference.
I have made a demo, wish it is useful to you.
Server end (console application).
class Program
{
static void Main(string[] args)
{
using (ServiceHost sh=new ServiceHost(typeof(MyService)))
{
sh.Opened += delegate
{
Console.WriteLine("Service is ready......");
};
sh.Closed += delegate
{
Console.WriteLine("Service is closed");
};
sh.Open();
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet]
string SayHello();
}
public class MyService : IService
{
public string SayHello()
{
return "Hello, Busy world"; }
}
App.config
<system.serviceModel>
<services>
<service behaviorConfiguration="Service1Behavior" name="VM1.MyService">
<endpoint address="" binding="webHttpBinding" contract="VM1.IService" behaviorConfiguration="rest" >
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:13008"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="rest">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Client(console app)
static void Main(string[] args)
{
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
try
{
Console.WriteLine(client.SayHello());
}
catch (Exception)
{
throw;
}
}
App.config
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="rest">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://10.157.13.69:13008/" binding="webHttpBinding" contract="ServiceReference1.IService" behaviorConfiguration="rest">
</endpoint>
</client>
</system.serviceModel>
We also need to add the WebGet attribute to the operation method.
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReference1.IService")]
public interface IService {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IService/SayHello", ReplyAction="http://tempuri.org/IService/SayHelloResponse")]
[WebGet]
string SayHello();
Result.
Feel free to let me know if there is anything I can help with.

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>

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

Bad Request Error On REST service Method call with POST (json Data)?

Hi i am new to the RESTful WCF I am trying to do the the simple call to the webservice method using POST here is my code
Service Interface code
[ServiceContract]
public interface IJsonSave
{
[OperationContract]
[WebInvoke(UriTemplate = "/SaveJason", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string SaveJason(string value);
}
web.config file code
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<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="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name ="JsonDataSave.JsonSave"
behaviorConfiguration ="servicebehavior" >
<endpoint name ="SOAPEndPoint"
contract ="JsonDataSave.IJsonSave"
binding ="basicHttpBinding"
address ="soap" />
<endpoint name ="RESTEndPoint"
contract ="JsonDataSave.IJsonSave"
binding ="webHttpBinding"
address ="Rest"
behaviorConfiguration ="restbehavior" />
<endpoint contract="IMetadataExchange"
binding="mexHttpBinding"
address="mex" />
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I tried using fiddler her are my Headers
POST http://localhost:50267/JsonSave.svc/Rest/SaveJason
User-Agent: Fiddler
Content-Type: application/json
Data-Type: json
Host: localhost:50267
Request Body :
({"value":"asdfasd"})
It gives error of HTTP/1.1 400 Bad Request and when debug detail enabled it gives following stack trace
The server encountered an error processing the request. The exception message is 'Error in deserializing body of request message for operation 'SaveJason'. The OperationFormatter could not deserialize any information from the Message because the Message is empty (IsEmpty = true).'. See server logs for more details. The exception stack trace is:
at System.ServiceModel.Dispatcher.PrimitiveOperationFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
I googled a lot and tried every solution there is available but it still didn't work any help would be great.And it works for the SOAP just gives error with REST!
In order to gather additional information about the data flow and location of the error you may benefit from enabling WCF Tracing on the service side. The following link should provide sufficient details: http://msdn.microsoft.com/en-us/library/ms733025(v=vs.110).aspx
Regarding the error in your scenario, I suspect that the message encoding is not set consistently for the client and service. I wonder if maybe the:
BodyStyle = WebMessageBodyStyle.WrappedRequest
should be either:
BodyStyle = WebMessageBodyStyle.Wrapped
or
BodyStyle = WebMessageBodyStyle.Bare
so the request and response have the same wrapping style.
Regards,

WCF MsmqIntegrationBinding - Some XML messages not being picked up

I am using a WCF service to pick up messages off of MSMQ. I have found that some of the messages are not being picked up and I am not sure why. How can I try to debug this? I don't see any errors being thrown, the service is just not picking up messages off o the queue. I am using MsmqMessage to enqueue / dequeue the messages.
Message size: 146,000 bytes (not that big).
What I have found: if I cut down the message size (delete some of the content). So it could be size related or it could be content. Nothing crazy in the xml though.
Any ideas?
Service Configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- use appSetting to configure MSMQ queue name -->
<add key="QueueName" value=".\private$\MyMessageQueue" />
<add key="baseAddress" value="http://localhost:8000/test/message" />
</appSettings>
<system.serviceModel>
<services>
<service behaviorConfiguration="MessageServiceBehavior" name="WcfServiceClient.MessageServiceClient">
<!-- .Net endpoint-->
<endpoint address="msmq.formatname:DIRECT=OS:.\private$\MyMessageQueue"
binding="msmqIntegrationBinding"
bindingConfiguration="DotNetBinding"
contract="WcfServiceClient.IMessageProcessor" />
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MessageServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata />
<!--<serviceThrottling maxConcurrentCalls="20" maxConcurrentSessions="20" />-->
<serviceTimeouts />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<msmqIntegrationBinding>
<binding serializationFormat="ActiveX" name="ActiveXBinding" durable="true" exactlyOnce="true">
<security mode="None" />
</binding>
<binding serializationFormat="Xml" name="DotNetBinding" durable="true" exactlyOnce="true">
<security mode="None" />
</binding>
</msmqIntegrationBinding>
</bindings>
</system.serviceModel>
</configuration>
EDIT:
When I turn on tracing (Just figured this out) I get this? Doesn't make any sense to me?
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
<EventID>131075</EventID>
<Type>3</Type>
<SubType Name="Error">0</SubType>
<Level>2</Level>
<TimeCreated SystemTime="2011-12-28T20:32:42.8874263Z" />
<Source Name="System.ServiceModel" />
<Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" />
<Execution ProcessName="WcfServiceClient.vshost" ProcessID="6316" ThreadID="12" />
<Channel />
<Computer>MyComputer</Computer>
</System>
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
<Description>Throwing an exception.</Description>
<AppDomain>WcfServiceClient.vshost.exe</AppDomain>
<Source>System.ServiceModel.Channels.TransportReplyChannelAcceptor+TransportReplyChannel/58366981</Source>
<Exception>
<ExceptionType>System.ServiceModel.CommunicationObjectAbortedException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The communication object, System.ServiceModel.Channels.TransportReplyChannelAcceptor+TransportReplyChannel, cannot be used for communication because it has been Aborted.</Message>
<StackTrace>
at System.ServiceModel.Channels.CommunicationObject.ThrowIfAborted()
at System.ServiceModel.Channels.InputQueueChannel`1.EndDequeue(IAsyncResult result, TDisposable& item)
at System.ServiceModel.Channels.ReplyChannel.EndTryReceiveRequest(IAsyncResult result, RequestContext& context)
at System.ServiceModel.Dispatcher.ReplyChannelBinder.EndTryReceive(IAsyncResult result, RequestContext& requestContext)
at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.EndTryReceive(IAsyncResult result, RequestContext& requestContext)
at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
at System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
at System.Runtime.InputQueue`1.Shutdown(Func`1 pendingExceptionGenerator)
at System.ServiceModel.Channels.InputQueueChannel`1.OnClosing()
at System.ServiceModel.Channels.CommunicationObject.Abort()
at System.ServiceModel.Dispatcher.ListenerHandler.AbortChannels()
at System.ServiceModel.Dispatcher.ListenerHandler.OnAbort()
at System.ServiceModel.Channels.CommunicationObject.Abort()
at System.ServiceModel.Dispatcher.ChannelDispatcher.OnAbort()
at System.ServiceModel.Channels.CommunicationObject.Abort()
at System.ServiceModel.ServiceHostBase.OnServiceHostFaulted(Object sender, EventArgs args)
at System.ServiceModel.Channels.CommunicationObject.OnFaulted()
at System.ServiceModel.Channels.CommunicationObject.Fault()
at System.ServiceModel.ServiceHostBase.OnChannelDispatcherFaulted(Object sender, EventArgs e)
at System.ServiceModel.Channels.CommunicationObject.OnFaulted()
at System.ServiceModel.Channels.CommunicationObject.Fault()
at System.ServiceModel.Dispatcher.ChannelDispatcher.OnListenerFaulted(Object sender, EventArgs e)
at System.ServiceModel.Channels.CommunicationObject.OnFaulted()
at System.ServiceModel.Channels.CommunicationObject.Fault()
at System.ServiceModel.Channels.Msmq4PoisonHandler.InternalFinalDisposition(MsmqQueue disposeFromQueue, MsmqMessageProperty messageProperty)
at System.ServiceModel.Channels.Msmq4PoisonHandler.FinalDisposition(MsmqMessageProperty messageProperty)
at System.ServiceModel.Channels.MsmqDecodeHelper.DecodeIntegrationDatagram(MsmqIntegrationChannelListener listener, MsmqReceiveHelper receiver, MsmqIntegrationInputMessage msmqMessage, MsmqMessageProperty messageProperty)
at System.ServiceModel.MsmqIntegration.MsmqIntegrationInputChannel.DecodeMsmqMessage(MsmqInputMessage msmqMessage, MsmqMessageProperty property)
at System.ServiceModel.Channels.MsmqInputChannelBase.TryReceive(TimeSpan timeout, Message& message)
at System.ServiceModel.Dispatcher.InputChannelBinder.TryReceive(TimeSpan timeout, RequestContext& requestContext)
at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.TryReceive(TimeSpan timeout, RequestContext& requestContext)
at System.ServiceModel.Dispatcher.ChannelHandler.TryTransactionalReceive(Transaction tx, RequestContext& request)
at System.ServiceModel.Dispatcher.ChannelHandler.TransactedLoop()
at System.ServiceModel.Dispatcher.ChannelHandler.SyncTransactionalMessagePump()
at System.ServiceModel.Dispatcher.ChannelHandler.OnStartSyncMessagePump(Object state)
at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
<ExceptionString>System.ServiceModel.CommunicationObjectAbortedException: The communication object, System.ServiceModel.Channels.TransportReplyChannelAcceptor+TransportReplyChannel, cannot be used for communication because it has been Aborted.</ExceptionString>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
</ApplicationData>
</E2ETraceEvent>
The exception
System.ServiceModel.CommunicationObjectAbortedException: The communication object, System.ServiceModel.Channels.TransportReplyChannelAcceptor+TransportReplyChannel, cannot be used for communication because it has been Aborted.
indicates, that the TransportReplyChannel has already been closed.
Can you provide the source code which shows how you read from the queue? Maybe there is an additional read after the queue object has been closed / disposed?

Categories

Resources