Friday, August 12, 2016

How to consume a Webservice in ASP.NET

In this article I will explain how to consume a Webservice.
In my following previous articles I have explained how to
create and authenticate a Webservice :

http://aspdotnetandmssqlserver.blogspot.com/2016/08/create-sample-webservice-in-c.html

http://aspdotnetandmssqlserver.blogspot.com/2016/08/authenticate-webservice-using-soap.html

Consider a Webservice hosted in local computer and
has to use a Webservice method in a website. Following
are the steps to be followed.

Open Website in Visual Studio. Right Click on Solution Explorer
and click "Add Web Reference...", you will get a screen like this :


Provide the url of the Webservice and Click "Go", it will display the
Webservice found at that URL. Provide Web Reference Name and
click "Add Reference". Then we can see the service reference as
follows in the folder, App_WebReferences :



















Consider a WebPage that has two textboxes and has to display Webservice's result
on Button click to a Label.

HTML Code (.aspx) :


<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <br />
        <asp:Button ID="Button1" runat="server" Text="Concatenate"
            onclick="Button1_Click" />
          <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>


C# Code (.aspx.cs) : 


Here is the server side C# code :


 protected void Button1_Click(object sender, EventArgs e)
 {
        localhost.Service1 srv = new localhost.Service1();
        localhost.AuthHeader authentication = new localhost.AuthHeader();

        authentication.Username = "KM123";
        authentication.Password = "q@s#d$a^";
        srv.AuthHeaderValue = authentication;

        Label1.Text=srv.Concatenate(TextBox1.Text, TextBox2.Text);
    }


I will explain the code. First we have to create an object of the service. Then

we have to create an object of the AuthHeader class and pass Username and 

password to that. Then add that AuthHeaderValue to the service. And call the 

service method which will return the output as :












Since code for Authentication is provided, if we pass wrong credentials,

it will display the output as :



No comments:

Post a Comment