Problem statement
Recently one of my friends has to regenerate the proxy classes added via Visual Studio Add Service Reference option to an ASMX WEB service. After regeneration of the proxy classes, he started getting "HTTP Error 401 - Unauthorized" error.
Temporary solution
He called out for a help. After looking carefully into the proxy file, we found that the manually added code in the reference.cs file was got overwritten with proxy class regeneration.
The error "HTTP Error 401 - Unauthorized" indicated that authentication details are perhaps missing while making a request to web service. But we couldn't find any authentication details passing code in the latest reference.cs file. Later we checked into File History, there was a difference. The authentication related methods were not present in the latest proxy class reference.cs file.
After we added the method to include the missing authentication details, the call to web service method started working.Auto generated web service proxy with manually edited code
It overrides the GetWebRequest() method in the same auto generated proxy class.
{
string authInfo = "authenticaiton";
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
request.Headers.Add(HttpRequestHeader.Authorization, authInfo);
return request;
}
Permanent solution
Proxy generation happens all the time when the corresponding web service undergoes change. So, the proxy generation was recurring process and whenever proxy generation we would be sitting and fixing the same errors caused by manual changes overwriting issue.
We ought to find out a permanent solution so that all the issues with web service proxy regeneration can be put to rest.
Here partial classes in C# came to our rescue. Added a new partial class and in that partial class, included all the code we were manually adding to proxy class after it got regenerated.
New code looked like below:
{
public partial class SameClassNameAsThatOfProxyClass
{
protected override WebRequest GetWebRequest(Uri uri)
{
string authInfo = = "authenticaiton";
HttpWebRequest request= (HttpWebRequest)base.GetWebRequest(uri);
request.Headers.Add(HttpRequestHeader.Authorization, authInfo);
return request;
}
}
}
From that point onwards, whenever web reference proxy classes were regenerated, we never faced the problem of manual code being overwritten issue. As the classes were being different, the manually added was never overwritten when the web reference proxy classes regenerated.
No comments:
Post a Comment