Skip to main content
 首页 » 编程设计

c#之将类对象传递给 WebService

2024年02月23日29hnrainll

如何将类“BL_Customer”的类对象“obj”从我的 Web 应用程序传递到我的 Web 服务 (ASMX) 中的函数“Insert()”,然后在 Web 服务中访问该对象的属性?我通过“添加 Web 引用”工具包含了我的远程 Web 服务。我已经包含了“使用 WebRererence;”命名空间也。任何帮助将不胜感激。

这是我在业务层中的 BL_Customer 类:

public class BL_Customer 
{ 
    public BL_Customer() 
    { 
 
    }   
    string c_Cust_Name = string.Empty;     
    string c_Mobile_no = string.Empty;     
    public string Cust_Name 
    { 
        get { return c_Cust_Name; } 
        set { c_Cust_Name = value; } 
    }   
    public string Mobile_no 
    { 
        get { return c_Mobile_no; } 
        set { c_Mobile_no = value; } 
    }  
 
} 

这是我的数据访问层:

public class DAL_Customer 
{ 
    public SqlConnection con = new SqlConnection(); 
    WebReference.Service objWEB = new WebReference.Service();  //objWEB -> Webservice object 
    Connection c = new Connection();  
    public DAL_Customer() 
    { 
    } 
    public int Customer_Insert(BL_Customer obj) 
    { 
      --------- 
      --------- 
        return objWEB.Insert(obj);  // Insert() is a function in my remote webservice  
    } 
} 

这是我的网络服务:

public class Service : System.Web.Services.WebService 
{    
   public Service () { 
    } 
 
    [WebMethod] 
    public string insert(**What should be here?**) 
    { 
        ----- 
        ----- 
 
    } 
} 

问候, 大卫

请您参考如下方法:

根据您用于构建网络服务的技术,可能有不同的方法来实现这一点。如果您使用现在已弃用的 ASMX Web 服务,您将添加一个方法,该方法将您需要的类作为参数:

[WebMethod] 
public void DoSomething(Person p) 
{ 
    ... 
} 

如果您正在使用 WCF,这是在 .NET 中构建 Web 服务的推荐技术,您将设计一个服务契约:

[ServiceContract] 
public interface IMyService 
{ 
    void DoSomething(Person p); 
} 

在这两种情况下,为了使用服务,您将在客户端生成一个强类型代理。再次推荐使用 Visual Studio 中的“添加服务引用”对话框,通过将其指向 Web 服务的 WSDL 来生成强类型代理。然后您将调用该方法:

using (var client = new MyServiceClient()) 
{ 
    Person p = new Person 
    { 
        FirstName = "john", 
        LastName = "smith" 
    }; 
    client.DoSomething(p); 
} 

如果您的客户端构建在 .NET 3.0 之前的版本上,您将需要使用 Visual Studio 中的“添加 Web 引用”对话框来生成客户端代理。