WCF Service in ASP.NET application generating intermittent 404 errors - wcf

This problem has defeated my attempts at Google, so here goes. We were having an issue getting data from a WCF service (just lookup data, so we enabled it for HTTP GET requests). Every once in while it will return a 404. The stack trace does NOT appear to have WCF in the mix - the StaticFileHandler appears to be attempting to serve it.
I created a a sample WCF service on ASP.NET 3.5 SP1 and am able to reproduce the problem. This is my sample service - the only differences from stock WCF at this point are the AspNetCompatibilityRequirements and the enabling of WebScript and HTTP GET:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string DoWork(string param1)
{
System.Threading.Thread.Sleep(150);
return "bar";
}
}
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet]
string DoWork(string param1);
}
Service config:
<service name="namespace.Service1">
<endpoint
behaviorConfiguration="WebScriptEnabled"
address="http://localhost:2961/svc/Service1.svc"
binding="webHttpBinding"
contract="namespace.IService1">
</endpoint>
</service>
Behavior config:
<behaviors>
<endpointBehaviors>
<behavior name="WebScriptEnabled">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
My node has aspNetCompatibilityEnabled="true">, but otherwise everything is pretty much OOB. I have no customizations on webHttpBinding at all.
If I F5 on VS 2008 using the built in web server and hit the URL, the very first request will result in a 404. If I continue to hit it with even a light load (7-10 simultaneous requests), I'll get a handful of 404 errors.
If I then let the load drop down to nothing and rerun my test, I can go to 50 simultaneous requests easily WITHOUT any errors.
My real service is much more complicated than this, but the fact that I can get a (nearly) stock sample to show this behavior is concerning, as though there might be a framework related issue. I've enabled WCF diagnostics and tracing but nothing shows in the logs (not unexpected since WCF is not in the stack trace when the 404 occurs).
I hope I'm doing something wrong and have not discovered a framework bug. My production environment is IIS6 and appears to exhibit the same behavior as my development server.

Related

What url is needed to consume WCF service

I have created a WCF service in Visual Studio 2010 and published it to a server running IIS 7.5.
It has one method - called returnNumber. This takes an int parameter called numberIn, multiplies it by 2 and returns the answer.
If I put
http://myserver/TestService/Service1.svc?wsdl
in a browser, it displays a page of XHTML.
What url should I use so that I can call my WCF service from a browser - passing a number in the QueryString so that the returnNumber method is called?
Further to responses below - Daniel - here is my code:
The web config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- 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>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
An IServicer1.cs file containing an interface:
namespace NumberTest
{
[ServiceContract]
public interface IService1
{
[OperationContract(IsOneWay = false)]
int returnNumber(int numberIn);
}
}
And Service1.svc.cs
namespace NumberTest
{
public class NumberService : IService1
{
public int returnNumber(int numberIn)
{
int returnValue = numberIn * 2;
return returnValue;
}
}
I have published the above to
http://myServer/TestService
and, if I add a reference to the WCF service from within a VS Web Application, the returnNumber method is exposed and works if I call it.
How do I allow people running web sites that are not asp.net (so they cannot add a service reference) to be able to call my returnNumber method and get a number back?
To pass arguments to a service on the querystring you are unfortunately not using the correct technology stack.
WCF exposes web operations across a SOAP 1.2 (by default) endpoint, which means that the web server expects a SOAP request (that is a soap envelope wrapping the XML request payload) directed to the services URL.
What you want to do is hook up a pure HTTP web service, for which the correct Microsoft technology stack is ASP.NET WebApi.
You can use the WCF Test Client (depending on the version of VS you are using), pop in the address for your WSDL, and use that to test your web serivce.
If you use the test client and a tool such as Fiddler, you could find out the URLs that are being used under the covers by looking for HTTP POSTs to your web service.
Regarding your second question, consuming your web service from a non-asp.net platform, you should only need to configure your service to provide the WSDL.
Non-.net platforms, aka Java, have tools, such as wsdl2java, that consume the WSDL and produce the necessary client code.
The tools and usage will vary depending on platform, but the following link should provide a valuable point of reference. http://axis.apache.org/axis2/java/core/docs/userguide-creatingclients.html
Regards,

Exposing a WCF Service as a COM+ Component

I am working with a client that has multiple Classic ASP websites, but would like to use AppFabric Caching within these sites to help lighten the load they currently have on their database.
The first approach we used was creating a .NET wrapper for the AppFabric API and exposing it to the ASP websites as a COM object. This method worked, but they soon began to experience high memory usage that crashed their webserver. The COM component is hosted within the application scope of the site so that could be a big part of the issue.
One of the options I came up with was creating a WCF Service and exposing it to the ASP sites as a COM+ Service. Unfortunately, my exposure to COM+ at this point is limited. My reasoning behind this is the service can be utilized from the ASP websites, but hosted out of process from the websites. This would also allow me to performance test the COM+ service independently from the websites.
I am having trouble coming up with start to finish documentation for creating and publishing the COM+ service. The MSDN documentation I’ve read appears to skip significant steps in the process.
As an example service I have the following:
namespace TestComService
{
[ServiceContract(SessionMode = SessionMode.Allowed, Namespace = "http://tempure.org/DD1F6C46-1A25-49CC-AA20-2D31A3D0C0AA", Name = "IService")]
public interface IServiceContract
{
[OperationContract]
string Get(string key);
[OperationContract]
void Set(string key, string value);
}
public class Service : IServiceContract
{
private readonly Dictionary<string, string> cache = new Dictionary<string, string>();
public string Get(string key)
{
return cache[key];
}
public void Set(string key, string value)
{
cache.Add(key, value);
}
}
}
The configuration is as follows:
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="comNonTransactionalBinding"/>
</netNamedPipeBinding>
</bindings>
<comContracts>
<comContract contract="{DD1F6C46-1A25-49CC-AA20-2D31A3D0C0AA}" name="IService" namespace="http://tempure.org/DD1F6C46-1A25-49CC-AA20-2D31A3D0C0AA" requiresSession="true">
<exposedMethods>
<add exposedMethod="Get"/>
<add exposedMethod="Set"/>
</exposedMethods>
</comContract>
</comContracts>
<services>
<service name="{3957AA9E-4671-4EF0-859B-1E94F9B21BEE},{5D180F85-65D8-4C0C-B5D6-9D28C59E29AE}">
<endpoint address="IService" binding="netNamedPipeBinding" bindingConfiguration="comNonTransactionalBinding" contract="{DD1F6C46-1A25-49CC-AA20-2D31A3D0C0AA}"/>
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/TestComService"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
I’m still a bit confused as far as hosting goes. Can this be hosted within IIS, or to I need to create a separate service to host within that?
Once again, I'm open to any suggestions or input someone with more experience with the matter can provide.
We use COM+ called directly from a web service and WCF Service. I do not believe you need to use a WCF wrapper, called from your ASP.NET application, to use the COM+ component unless it will run on a different server.
You need to install the COM+ component separately from the Web App on the server. It must be registered in the GAC. You create a reference to the COM+ object/DLL file in your ASP.NET application. When you call the DLL file it uses the deployed object registered in the GAC which calls the registered COM+ object.
We had some problems with the native .NET installer. It does not always register the COM+ component correctly. So I wrote a simple batch file that does the job. Here is batch code. I deploy regsvsc.exe with the application so it always knows where to find it.
regsvcs /fc MYCOM+.DLL

Consuming Web Service from WCF

I have created a WCF service, now this WCF service has to call a Web Service. What I am doing is adding the service reference of web service in WCF and calling the method of the web service which I want to use.
Just an example shown below :
CalcWebReference.CalculatorSoapClient fct =
new CalcWebReference.CalculatorSoapClient();
int rq = fct.Add(q, r);
return rq;
Now this method when I tried to call from the client it is giving following error
The server was unable to process the
request due to an internal error. For
more information about the error,
either turn on
IncludeExceptionDetailInFaults (either
from ServiceBehaviorAttribute or from
the configuration
behavior) on the server in order to
send the exception information back to
the client, or turn on tracing as per
the Microsoft .NET Framework 3.0 SDK
documentation and inspect the server
trace logs.
Thanks i did what u told but now i am getting following error "Could not find default endpoint element that references contract 'CalcWebReference.CalculatorSoap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element."
Now do i need to give some end points in the WCF service or in the web service to get the function from web service and if so then how do i give it.
Please help.
Hi,
CalcWebReference.CalculatorSoapClient is reffering to the web service not WCF.
Given below is the code written in WCF(sample code) which is calling the web service :-
CalcWebReference.CalculatorSoapClient fct = new CalcWebReference.CalculatorSoapClient();
int rq = fct.Add(12, 10);
return rq;
Am i not putting the syntax right or is there any additional thing that i need to do in this?
This is the generic WCF "something bad happened" error message. That won't really be much help.
Approaches:
make sure the web service you're calling works on its own - otherwise fix it!
enable the detailed error information, as described in the error message, by including the error details in your WCF service (do this in DEV environments only! Never in production...)
try to launch your WCF service inside Visual Studio and debug what's happening
In order to enable detailed error reporting, you need to add this section to your WCF service's configuration:
<behaviors>
<serviceBehaviors>
<behavior name="DebugBehavior">
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
You might already have a service behavior configured - in that case, just add the <serviceDebug> tag to your service behavior.
If you don't have a service config yet - you'll also need to make sure your service actually uses that service config:
<service name="YourServiceNameHere"
behaviorConfiguration="DebugBehavior">
Make sure to have a behaviorConfiguration= attribute on your <service> tag, and make sure to reference that defined service behavior (by specifying its <behavior name="..." > property).
Once you've done that, your error should hopefully give you more information - you should definitely get an .InnerException on your exception that should point you in the right direction.

How to get working path of a wcf application?

I want to get the working folder of a WCF application. How can I get it?
If I try
HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath)
I get a null reference exception (the Http.Current object is null).
What I meant with the working folder was the folder where my WCF service is running. If I set aspNetCompatibilityEnabled="true", I get this error:
The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.
I needed the same information for my IIS6 hosted WCF application and I found that this worked for me:
string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
As always, YMMV.
Please see ongle's answer below. It is much better than this one.
Updated after more information
The following worked for me. I tested it with a new WCF Service I hosted on IIS through a Service1.svc.
Add <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> to web config. <system.serviceModel>..</ ..> existed already.
Add AspNetCompatibilityRequirementsAttribute to the service with Mode Allowed.
Use HttpContext.Current.Server.MapPath("."); to get the root directory.
Below is the full code for the service class. I made no changes in the IService1 interface.
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public void DoWork()
{
HttpContext.Current.Server.MapPath(".");
}
}
And below is an excerpt from the web.config.
<system.serviceModel>
<!-- Added only the one line below -->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<!-- Everything else was left intact -->
<behaviors>
<!-- ... -->
</behaviors>
<services>
<!-- ... -->
</services>
</system.serviceModel>
Old answer
What do you mean by the Working Folder? WCF services can be hosted in several different ways and with different endpoints so working folder is slightly ambiguous.
You can retrieve the normal "Working folder" with a call to Directory.GetCurrentDirectory().
HttpContext is an ASP.Net object. Even if WCF can be hosted on IIS, it's still not ASP.Net and for that reason most of the ASP.Net techniques do not work by default. OperationContext is the WCF's equivalent of HttpContext. The OperationContext contains information on the incoming request, outgoing response among other things.
Though the easiest way might be to run the service in ASP.Net compatibility mode by toggling it in the web.config. This should give you access to the ASP.Net HttpContext. It will limit you to the *HttpBindings and IIS hosting though. To toggle the compatibility mode, add the following to the web.config.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
Depending on what you want. I usually want to resolve a url like "~/folder/file". This is what worked.
System.Web.Hosting.HostingEnvironment.MapPath("~/folder/file");
More general, I am using this one
AppDomain.CurrentDomain.BaseDirectory
The aspNetCompatibilityEnabled="true" should have resolved my problem, but I got this error:
The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.
I resolved my problem with getting the physical path of my running WCF service by getting it from my current app domain:
AppDomain.CurrentDomain.BaseDirectory
In order to reference ASP.NET features like the HttpContext object, you need to run your WCF app in ASP.NET compatibility mode. This article explains how to do this.
Use HostingEnvironment.ApplicationPhysicalPath in WCF to find your application physical path.
Use namespace
using System.Web.Hosting;

404 BadRequest exposing WCF service through external IP using IIS host headers

We host a WCF webservice on Windows Server 2003. This server only has 2 internal IP's. We want to expose the service externally. This is done through the firewall that maps an external IP to the service.
So, I would need to modify the service to display that external IP for the internal links. This is not an issue since it should only be used externally.
Changing the Host Header value in IIS gives a 'Bad Request (Invalid Hostname)' response from IIS. I also added an 'address' value to the endpoint entry in the web.config ... but it sill just points to the internal machine name. Any ideas?
edit: I can verify that IIS7 has the exact same behaviour. Address didn't work. Different hostname gave Invalid Hostname error. Is there seriously no way to present a different (fictive) IP? :/
edit2:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicAnonymous">
<security mode="None"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="Extended">
<serviceMetadata httpGetEnabled="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
</behavior>
</serviceBehaviors>
</behaviors>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="false" logMessagesAtServiceLevel="false" logMessagesAtTransportLevel="true" maxMessagesToLog="3000"/>
</diagnostics>
<services>
<service behaviorConfiguration="Extended" name="AnCWCFWebService.ProductInfoProvider">
<endpoint address="" binding="basicHttpBinding" name="ASMX" bindingConfiguration="BasicAnonymous" contract="AnCWCFWebService.Interfaces.IProductInfoProvider"/>
</service>
</services>
</system.serviceModel>
404 BadRequest Due to IIS Configuration...
If you are receiving a 404 BadRequest error from IIS after attempting to modify host headers in IIS, this is common, but there is a fix!
Fix By Making IIS Configuration Changes
How can WCF support multiple IIS Binding specified per site?
Fix By Making WCF Code Modifications
Alternatively, the following article explains how one developer solved this issue with a combination of configuration and code:
Well, that was fun! An adventure in WCF, SSL, and Host Headers
http://geekswithblogs.net/rakker/archive/2008/07/03/123562.aspx
The article references two important links...
The first one explains how to properly set the host headers in IIS:
Configuring Server Bindings for SSL Host Headers (IIS 6.0): http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/8d9f2a8f-cd23-448c-b2c7-f4e87b9e2d2c.mspx?mfr=true
After getting host headers working, you'll find that...
"you can't have more than one host
header for IIS or wcf will break"
The solution to working around this limitation is found within this article, and there is also a comment on the GeeksWithBlogs.net article above that provides an enhanced variation:
WCF: This collection already contains
an address with scheme http
If you are still experiencing trouble, let us know in the comments below...
If the Service is Not Working...
My experience with WCF is that it is very tricky at times, especially with configuration. If one is following best practices and not doing anything non-standard, the great majority of deployment problems are the result of a botched configuration file.
In theory (not so much in practice, due to architectural differences), setting up a WCF service on IIS should be no different than setting up a typical virtual directory and corresponding application for web application or for an ASMX web service.
Therefore, I recommend that if this is the first WCF service you are exposing to the Internet, follow the same simple approach you would take when exposing your first website. Basically, create a new sample "WCF Service Application" (this is available in the Add New Project dialog, under the Web section of C# or VB).
Once you have it working, follow your deployment practices to move it into a production sandbox and test it locally. This sandbox would preferably already have some web sites or web services installed and known to be accessible from the Internet, in order to eliminate any doubt about the typical network configuration issues. If you have a sample ASMX web service that is already successfully exposed on the Internet from that server, that would be best.
Next, try testing the the ASMX and the WCF services from web browser, both locally on the server, internally on other desktops and then finally externally.
Testing URLs
We want to test accessing the standard SVC and ASMX file from the web browser in all the varieties of URL flavors that are available and relevant. The results should be similar, with summary page about he service rendering in the window. The difference will be that the ASMX web service's summary will likely allow you to execute the web methods on the service if that feature has not been disabled in the web.config file.
Compare the results of browser fetches of the following styles of URLs...
http://localhost/WcfService1/Service1.svc
http://localhost/WcfService1/Service1.asmx
http://MachineName or MachineFQN/WcfService1/Service1.svc
http://MachineName or MachineFQN/WcfService1/Service1.asmx
http://MachineLocalIP#1/WcfService1/Service1.svc
http://MachineLocalIP#1/WcfService1/Service1.asmx
http://MachineLocalIP#2/WcfService1/Service1.svc
http://MachineLocalIP#2/WcfService1/Service1.asmx
http://ExternalIP/WcfService1/Service1.svc
http://ExternalIP/WcfService1/Service1.asmx
All of these tests should return similar results.
Testing Service Methods
If you feel like it, go head and test some web methods on the ASMX web service for any of the tested URLs, from the web browser. You'll soon see that we can test ASMX web services a different way also...
Next we'll test web methods on both the WCF service and the ASMX web service by using the WcfTestClient.exe application that is found in the Visual Studio 2008 distribution (C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE).
You will need to add the services through the File->Add Service menu item, typing in the URL above for each service URL that you wish to test. Make sure to include the filename of the SVC and ASMX files. If all is well, the MEX endpoint that is enabled by the "httpGetEnabled" attribute of the <serviceMetadata/> element in the web.config file will return the data that is necessary for the utility to operate, thereby populating the tree with the inventory of our service methods like this:
From this point, it will be useful to refer to the following to resources:
WCFTestClient: http://msdn.microsoft.com/en-us/library/bb552364.aspx
What's New for WCF in Visual Studio 2008: http://msdn.microsoft.com/en-us/magazine/cc163289.aspx
Conclusion
If you make it this far, then I do not expect any other issues and you should now attempt to compare the setup of the samples to the WCF service that you are attempting to publish to the Internet, and hopefully the differences will be obvious.
Remember to treat the WCF service like an ASMX web service during you diagnostics, assuming that the web.config is known to be set up correctly.
If you are still unable to make things work, check this guide for further technical advice:
Deploying an IIS-hosted WCF service: http://msdn.microsoft.com/en-us/library/aa751792.aspx
Finally, if all else fails, just wrap your WCF service in an ASMX web service:
How to: Expose WCF service also as ASMX web-service: http://kjellsj.blogspot.com/2006/12/how-to-expose-wcf-service-also-as-asmx.html
You just need to configure your host header in the IIS so that the links in the WSDL references will use the donmain name rather local machine name.
Check out
Steps to configure IIS host header so that WCF will use domain name in WSDL references.
Why not just assign a new IP address to the server instead of messing around with hostnames? A Windows Server can have multiple IP addresses for the same NIC.
Here is an article that talks about it.