问题描述:在设计WebService提供接口供用户去调用,但当方法参数传递为一个类时,需要在WebService类中 传递出一个类来供参数使用。同使要保证其可序列化。
首先写一个测试类Staff,如下:
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;
namespace
HMClass
{
/// <summary>
/// Summary description for Staff
/// </summary>
public class Staff
{
// 定义属性
private int intID = 0;
private string strName = "";
private string strDes = "";
private string strAddress = "";
//属性
public int IntID
{
get { return intID; }
set { intID = value; }
}
public string StrName
{
get { return strName; }
set { strName = value; }
}
public string StrDes
{
get { return strDes; }
set { strDes = value; }
}
public string StrAddress
{
get { return strAddress; }
set { strAddress = value; }
}
public Staff()
{
//
// TODO: Add constructor logic here
//
}
}
}
然后完成WebService类如下:
using
System;
using
System.Web;
using
System.Collections;
using
System.Web.Services;
using
System.Web.Services.Protocols;
using
System.Xml.Serialization;
/// <summary>
/// Summary description for Class2WebService
/// </summary>
[WebService(Namespace
=
"
http://tempuri.org/
"
)]
[WebServiceBinding(ConformsTo
=
WsiProfiles.BasicProfile1_1)]
public
class
Class2WebService : System.Web.Services.WebService
{
public Class2WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[Serializable]
public class oStaff : HMClass.Staff //继承自HMClass.Staff
{
public oStaff()
{
}
}
[XmlInclude(typeof(oStaff))]
[WebMethod]
public string Display(oStaff m) //处理方法
{
string str;
str = m.IntID + m.StrAddress + m.StrDes + m.StrName; //简单的将字符串连接
return str;
}
}
注:
1. 类oStaff前一定要加上 [Serializable],使类可序列化。
2. WebMethod前要加上 [XmlInclude(typeof(oStaff))]否则在调用处无法声明。并引入 using System.Xml.Serialization;
现在可以调用WebMethod。测试页面代码。
using
System;
using
System.Data;
using
System.Configuration;
using
System.Collections;
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;
public
partial
class
ClassWS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ClsWS.Class2WebService ws2 = new ClsWS.Class2WebService();
//HMClass.Staff m; //在本地的一个同样的类是无法识别的
ClsWS.oStaff mm = new ClsWS.oStaff();
mm.IntID = 1;
mm.StrAddress = "China";
mm.StrDes = "SE";
mm.StrName = "Jason";
Response.Write(ws2.Display(mm)); //测试
}
}
}
例子非常简单,只为提供一个思路。
WebService参数传递类实例


2345

被折叠的 条评论
为什么被折叠?



