如何在WebService中重载方法

来源:互联网 发布:算法导论第四版答案 编辑:程序博客网 时间:2024/06/11 19:47

1. 本来在WebService中这样写的重载方法,如下所示:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class DataObjectWebService : System.Web.Services.WebService
    {
        [WebMethod(EnableSession = true)]
        public int Add(int a, int b)
        {
            return a + b;
        }

        [WebMethod(EnableSession = true)]
        public int Add(int a, int b, int c)
        {
            return a + b + c;
        }
    }

在调用WebService时,抛错:“Int32 Add(Int32, Int32, Int32) 和 Int32 Add(Int32, Int32) 同时使用消息名称“Add”。使用 WebMethod 自定义特性的 MessageName 属性为方法指定唯一的消息名称。”

2. 原来,必须在类中指示不支持1.1标准并且在方法中指定MessageName来创建唯一的别名。可以这样来解决,如下所示,这样在客户端调用时,就可以调用WebService不同的重载方法了。

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.None)]
    public class DataObjectWebService : System.Web.Services.WebService
    {
        [WebMethod(EnableSession = true, MessageName= "Add1")]
        public int Add(int a, int b)
        {
            return a + b;
        }

        [WebMethod(EnableSession = true, MessageName= "Add2")]
        public int Add(int a, int b, int c)
        {
            return a + b + c;
        }
    }

其中,

WebServiceBindingAttribute.ConformsTo 属性:获取或设置绑定声称所符合的 Web 服务互操作性 (WSI) 规范。

WsiProfiles.None 表示 Web 服务未提出任何一致性声称。

WsiProfiles.BasicProfile1_1 表示 Web 服务声称符合“WSI 基本概要”1.1 版。

WebMethodAttribute.MessageName 属性:在传递到 XML Web services 方法和从 XML Web services 方法返回的数据中用于 XML Web services 方法的名称。默认值是 XML Web services 方法的名称。 另外,MessageName 属性可用于为方法或属性名创建别名。MessageName 属性 (Property) 最常用来唯一标识多态方法。默认情况下,MessageName 设置为 XML Web services 方法的名称。因此,如果 XML Web services 包含两个或更多同名的 XML Web services 方法,则可唯一确定各个 XML Web services 方法,处理方法是将 MessageName 设置为 XML Web services 内的唯一名称,而不用在代码中更改实际方法的名称。数据在传递到 XML Web services 时通过请求发送,而在返回时则通过响应发送。在请求和响应中,用于 XML Web services 方法的名称是其 MessageName 属性 (Property)。与 XML Web services 方法关联的消息名称必须在 XML Web services 内是唯一的。如果在客户端调用初始方法后添加同名但具有不同参数的新 XML Web services 方法,则应为新方法指定不同的消息名称,但应原样保留初始消息名称,以确保与现有客户端兼容。

0 0