[c#]Webservice中如何实现方法重载(overload)以及如何传送不能序列化的对象作参数

1。Webservice中的方法重载问题
(1)在要重载的WebMethod上打个MessageName标签
比如:
[WebMethod(MessageName = "HelloWorld1")]
public string HelloWorld(){
    return "HelloWorld";
}

[WebMethod(MessageName = "HelloWorld2")]
public string HelloWorld(string msg){
    return msg + "HelloWorld";
}
(2)此外还要在class上修改WebServiceBinding特性,如下:
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
    public class UploadService : System.Web.Services.WebService
    {
        ...
    }

2.无法序列化的对象如何作为参数传递
比如:
void TestMethod(MyObject p){
    ...
}
这里MyObject是一个自定义类,并且无法序列化,如果你的WebService里有这样的方法,那么在浏览asmx时,会提示“MyObject无法序列化,因为没有无参数的构架函数”之类,解决办法有二个:
(a)修改MyObject,使其序列化,但如果MyObject已经封装成程序集(dll)无法修改的话,请看第二种方法
(b)将void TestMethod(MyObject p)修改为

void TestMethod(Object t){
    MyObject p = t as MyObject
    ...
}
即把Object做为参数传入,然后在方法内部再Cast为MyObject,虽然这要增加了额外的拆箱,封箱操作,但总比不能用要好

另外,讲几个小技巧,如果要给方法增加描述说明,让引用webService的人更容易看懂,可以在[WebMethod(MessageName = "HelloWorld1")]后再增加一个Desciption="xxx",即
[WebMethod(MessageName = "HelloWorld1", Description = "描述内容,支持Html语法哦")]

同样整个WebService也可以增加描述,在class上增加Desciption属性,即
    [WebService(Namespace = "http://www.yourdomain.com/",Description="服务说明,支持html语法")]
    [WebServiceBinding(ConformsTo = WsiProfiles.None)]
    public class UploadService : System.Web.Services.WebService
    {
        ...
    }

posted @ 2008-04-17 21:23  菩提树下的杨过  阅读(3541)  评论(2编辑  收藏  举报