Navigation

Sunday 14 April 2013

Web Service in ASP.NET

How we can create a basic web service and consume it in asp.net

STEP 1: Create a Web Service in your Visual Studio and code this in Service.cs


using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService
{
    public authHeader au;
    public Service()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [SoapHeader("au", Required = true)]
    [WebMethod]
    public string data()
    {

        if (au.userName == "vijay")
        {
            return "Hello World";
        }
        else
        {
            return "error";
        }
    }


    public class authHeader : SoapHeader
    {
        public string userName = "vijay";
        public string passWord = "Prajapati";

    }
}


STEP 2: Run this web-services and copy the url

STEP 3:Create a new web site in asp.net and add "Add Service Reference " by clicking on "WebSites" in menu bar. When window of Add Service Reference is open click on "Advanced.." at botton of window,then a new window of service reference setting is opened there you find the "Add Web Reference" and by clicking on button Add Web Reference u got the new  window of "Add Web Reference"

STEP 4: When "Add Web Reference" Window open past the url ,that you copy from web services and press the appropriate button and it will added

STEP 5 : Code this in your default.aspx page


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.ServiceModel;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        localhost.Service  s = new localhost.Service();
        localhost.authHeader a = new localhost.authHeader();
        a.userName ="vijay";
        a.passWord ="prajapati";
        s.authHeaderValue = a;

        Label1.Text = s.data();

    }
}


for more details

No comments:

Post a Comment