【问题标题】:how to pass object into web service and consuming that web service如何将对象传递到 Web 服务并使用该 Web 服务
【发布时间】:2010-09-20 08:34:12
【问题描述】:

考虑下面的代码..

[Serializable]
public class Student
{
    private string studentName;
    private double gpa;

    public Student() 
    {

    }

    public string StudentName
    {
        get{return this.studentName;}
        set { this.studentName = value; }
    }

    public double GPA 
    {
        get { return this.gpa; }
        set { this.gpa = value; }
    }


}

私有 ArrayList studentList = new ArrayList();

    [WebMethod]
    public void AddStudent(Student student) 
    {
        studentList.Add(student);
    }

    [WebMethod]
    public ArrayList GetStudent() 
    {
        return studentList;
    }

我想使用简单的 C# 客户端表单应用程序来使用该 Web 服务。 我无法使用以下代码段获取学生列表..

MyServiceRef.Student student = new Consuming_WS.MyServiceRef.Student();

    MyServiceRef.Service1SoapClient client = new Consuming_WS.MyServiceRef.Service1SoapClient();

任何想法..??

提前致谢!

【问题讨论】:

  • 您是否遇到任何异常/错误?您没有调用 Web 服务的 GetStudent() 方法。如果我们从 Web 服务返回 C# ArrayList,我们真的可以从其他平台的客户端使用相同的 ArrayList 吗?说Java客户端?
  • 是的,我知道..但问题是我不能分配这样的东西.. ArrayList studentList = new ArrayList(); studentList = client.GetStudent();此代码段不起作用!任何想法..?

标签: c# web-services


【解决方案1】:

问题在于您的 Web 服务不是无状态的。每次调用 Web 服务时,都会实例化 Web 服务类的新实例,并在此实例上调用方法。当实例被调用时,studentList 被分配一个新的空列表。

您需要更改状态管理。例如。

private static ArrayList studentList = new ArrayList();

可能会更好,但它仍然不可靠。 查看http://www.beansoftware.com/asp.net-tutorials/managing-state-web-service.aspx 的文章以获取将状态存储在 Session(或 Application)中的示例。

编辑:添加示例代码以避免使用 ArrayList。

为了避免 ArrayList 和 ArrayOfAnyType 出现问题:

private List<Student> studentList = new List<Student>();

[WebMethod]
public void AddStudent(Student student) 
{
    studentList.Add(student);
}

[WebMethod]
public Student[] GetStudent() 
{
    return studentList.ToArray();
}

【讨论】:

  • :: Nop..问题仍然存在。它说..“无法将类型 'Consuming_WS.MyServiceRef.ArrayOfAnyType' 隐式转换为 'System.Collections.ArrayList'”...任何想法..??
  • 查看我在上面添加的示例以解决此问题。问题是您在 Web 服务接口中使用 ArrayList。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多