关于WebService的一些注意事项

    1.WS须支持可序列化的对象,对泛型 支持不够

    2.WS的发部  :  先 生成网站,再  发部网站。

    以下是WS的一些代码

using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
   public Service () {

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

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


/// <summary>
/// 没有【WebMethod】则为内部方法
/// </summary>
/// <returns></returns>
[System.Web.Script.Services.ScriptMethod]
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;

}

/// <summary>
/// web Service对现有的泛型支持不够,将以用字符串数组替换
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
[WebMethod]
public List<string> GetCollection(int m)
{
Random r = new Random();

List<string> list=new List<string>();

for(int i=0;i<m;i++)
{
list.Add(r.Next(1,100).ToString());
}

return list;
}

    [WebMethod]
 public DataTable GetProducts(int CategoryID)
  {
     SqlConnection sqlcon = new SqlConnection("server=.;uid=sa;pwd=;database=NorthWind");
     sqlcon.Open();

     SqlDataAdapter sda = new SqlDataAdapter("select * from Product where 类别ID="+CategoryID,sqlcon);
     DataSet ds = new DataSet();
     sda.Fill(ds,"temp");
     sqlcon.Close();

     return ds.Tables["temp"];
   }
}

3.在项目中调用WS

     先在项目中添加Web引用,将Ws 服务地址的URL 如:http://lockhost/ibeifeng/service.asmx ,更改Web 引 用名(如:localhost),添加引用。

4.具体调用,假设置WS引用名为localhost

protected void Button1_Click(object sender, EventArgs e)
{
    //生成代理类
    localhost.Service ws = new localhost.Service();
    //测试服务1
    //Response.Write(ws.HelloWorld());

    //测试服务2
    //Response.Write(ws.Add(10,6));

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

    //测试服务4
    this.GridView1.DataSource = ws.GetProducts(int.Parse(this.TextBox1.Text));
    this.GridView1.DataBind();
}

     

原文地址:https://www.cnblogs.com/yingger/p/2518120.html