Friday 9 March 2012

Protocol Violation Exception raised while using PHP webserivce in .net project

In one of our asp.net 3.5 project we were using PHP services. Whenever a request to PHP service was made we were alternatively getting following exception:
"System.Net.WebException: The server committed a protocol violation. Section=ResponseStatusLine"

After googling and refering to related sites we tried setting useUnsafeHeaderParsing in web.config to true. But this didnt solve this issue.

<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true" />
</settings>
</system.net>


Reason for the above exception was that the request headers were  changing in the consequtive requests and this was not validated by HTTP 1.1 protocol. To resolve this we created a custom class that inherits the proxy class (auto-generated by Visula Studio). In this class WebRequest method was overridden and the HTTP protocol version was changed to 1.0 and the property KeepAlive was set to false. In HTTP/1.1 a keep-alive-mechanism was introduced, where a connection could be reused for more than one request. By setting KeepAlive to false a new connection was created with every request.

public class checkSiteUserEmailBindingCustom: wsPHPWebsite.checkSiteUserEmailBinding
        {
            private static PropertyInfo requestPropertyInfo = null;

            public checkSiteUserEmailBindingCustom() { }

            protected override System.Net.WebRequest GetWebRequest(Uri uri)
            {
                // Retrieve underlying web request
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
                webRequest.KeepAlive = false;
                webRequest.ProtocolVersion = System.Net.HttpVersion.Version10;

                return webRequest;
               
            }
        }



If we drill down the web services classes all the classes directly/indirectly belongs to System.Web.Services.Protocol namespace. Base class for all XML web service client proxies is WebClientProtocal class. This is an abstract class and contains a virtual method GetWebRequest. 
WebClientProtocal class is inherited by HTTPWebClientProtocol. This is an abtract base class for all XML Web service client proxies that use the HTTP transport protocol. This class is further inherited by  System.Web.Services.Protocols.SoapHttpClientProtocol. This is the  class which proxies derive while using SOAP protocol. This class Overrides HttpWebClientProtocol.GetWebRequest(Uri).


Reference URLs:
http://forums.asp.net/t/1223296.aspx/1
http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx
http://msdn.microsoft.com/en-us/library/system.web.services.protocols.webclientprotocol.aspx
http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

No comments:

Post a Comment