微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WebService

一、理解Web Service :Web服务就是一组方法

1、Web Service: 是可互操作的分布式应用程序(跨语言,跨平台)

2、Web Service: 使用HTTP 和 XML 进行通信

3、Web Service: 可以穿越防火墙,真正实现自由通信

4、通过SOAP实现异地调用(跨地域)

 

二、Web service 的开发步骤

1、创建Web service

     (1)、新建

 Web Service网站

     (2)、Service.asmx的文件,这就是webservice的标准文件

       

      

       (3)、打开服务类: App_Code文件夹中的Service.cs 文件

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

        //如果使用设计的组件,请取消注释以下行
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

    /// <summary>
    /// 没有[WebMethod]则为内部方法
    /// </summary>
    /// <returns></returns>
    public string Hello()
    {
        return "Hello";
    }

    [WebMethod]
    public int add(int m,int n)
    {
        return m + n;
    }

    [WebMethod]
    public string[] GetRandom(int m)
    {
        Random r = new Random();
        string[] str = new string[m];
        for (int i = 0; i < m; i++)
        {
            str[i] = r.Next(1,100).ToString();
        }
        return str;
    }

    [WebMethod]
    public DataTable GetColumn(int ParentId)
    {
        sqlConnection sql = new sqlConnection("server=.;uid=sa;pwd=;database=LTArticle");
        sqlDataAdapter sda = new sqlDataAdapter("select * from LT_Column where ParentId=" + ParentId,sql);
        DataSet ds = new DataSet();
        sda.Fill(ds,"temp");
        return ds.Tables["temp"];
    }

}

 

   (4)、测试

    

     

2、发布Web service

 

 

3、调用Web service

(1)、新建ASP.NET网站

   

(2)、添加 Web引用

  

(3)、url 填写 Webservice引用的地址---》前进---》添加引用

 

(4)、

 

(5)、打开Default.aspx页面添加按钮,DropDownList控件,GridView控件

    protected void Button1_Click(object sender,EventArgs e)
    {
        //生成代理类
        localhost.Service ws = new localhost.Service(); //localhost代理文件的命名空间,Service是WebService中的类
        //测试服务1
        //Response.Write(ws.HelloWorld());

        //测试服务2
        //Response.Write(ws.add(10,5));

        //测试服务3
        //DropDownList1.DataSource = ws.GetRandom(5);
        //DropDownList1.DataBind();

        //测试服务4        GridView1.DataSource = ws.GetColumn(0);        GridView1.DataBind();    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐