Google Search

Thursday, June 26, 2008

Consuming HTTPS web service using c# and asp.net

I have been trying this for this for the whole past week and finally got a solution, what I was provided was a https wsdl file and had to consume it. I tried a lot in ASP and could not find any solution and came up with consuming the web service using .NET 2.0 using C# and asp.net

The webservice provided was something like this:
https://xx.xxx.xxx.xxx/test/services/sum?wsdl"

The main issue was to handle the certificates, if we use https.

Suppose you have a function sum which returns sum of two numbers if provided as parameters in the wsdl definition.

To start with create a new website in Visual Studio (select Framework 2.0 if using VS 2008).
Create a web reference. Go to Project>>Add Web Reference.
A new Window will open here give the https link i.e https://xx.xxx.xxx.xxx/test/services/sum?wsdl and press the GO button. You will get those Certificate pop ups, select OK and accept then you can see the all the function in the description.
Provide a name let it be "web.sumref" and click on AddReference button.
Now go to default.aspx.cs file.
Here add the namespace "using web.sumref"
To resolve the issue with Certificates you need to implement the a class that impements ICertificatePolicy interface. Using this class we can return true so that it accepts all certificates.
For this you need to use the namespace:
using System.Security.Cryptography.X509Certificates;
And you need to call the CheckValidationResult before you call the web service.

Here is the code for default.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using web.sumref;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
using System.Xml;
public partial class _Default : System.Web.UI.Page {

//create object for web service
SumWebService obj = new SumWebService();
protected void Page_Load(object sender, EventArgs e) {
ServicePointManager.CertificatePolicy = new MyCertificateValidation();
int sum=obj.sum(2,3);
Response.Write(sum.ToString());
}
public class MyCertificateValidation : System.Net.ICertificatePolicy{
//This class handles problems with certificates if ssl (https) is used
bool ICertificatePolicy.CheckValidationResult(ServicePoint srvPoint, X509Certificate cert, WebRequest request, int problem) {

return true;
// Accept all certificates
}
}

No comments: