【问题标题】:Web Service code not returning array of StringWeb 服务代码不返回字符串数组
【发布时间】:2011-07-30 17:35:52
【问题描述】:

我想从我的 Web 服务方法返回一个格式为“abc#xyz#ghi#tru”(其中 # 是分隔符)的字符串数组。但是我做不到。这是我当前的网络服务代码:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace WebService10
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment
 the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        String[] result=new String[40];
        String[] result2 = new String[40];

        [WebMethod]
        public String[] getData()
        {
            SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
            try
            {
                myConnection.Open();

                SqlCommand myCommand = new SqlCommand();
                myCommand.Connection = myConnection;
                myCommand.CommandText = "select count(*) from names where name =@name";

                SqlDataReader myReader = myCommand.ExecuteReader();

                //while
                for(int i=0;i<40;i++)
                {
                    if (myReader.Read())
                    {
                         result[i]= myReader["name"].ToString();
                         result2[i] = result[i] + "#";
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                myConnection.Close();
            }

            return result2;
        }
    }
}

谁能告诉我我的代码有什么问题?

【问题讨论】:

  • 那是很多代码。它在做什么?如果您将 getData() 更改为仅返回一个静态值,例如“返回的字符串”,会发生什么?{
  • 嘿,对不起,我会解释的。我在 SQL Server 2008 中创建了一个数据库,其中有一个“名称”列,我在其中插入了示例值。我只想以我在问题中提到的形式以及分隔符来检索这些值。有什么办法吗?
  • 你想从你的单列中获取所有的名字吗?
  • @kleinohad:是的,我有单列“名称”,其中包含我已经插入的值。我现在只需要按照我在帖子中提到的方式使用我的网络服务的方法来检索它们
  • 是否有充分的理由用“#”而不是标准逗号分隔? (因为您可以依靠网络服务为您序列化您的数组,而不是进行字符串连接)

标签: .net web-services visual-studio-2008


【解决方案1】:

试试这个:

我更改了查询(顺便说一句:查询仍然没有多大意义,但我不知道您真正想要什么)、结果类型和循环。

您也忘记将参数传递给查询。

另外:改变异常处理;在服务器端写入控制台不是一个好主意。

public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    public String getData(string nameFilter)
    {
        String result = "";

        SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
        try
        {
            myConnection.Open();

            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandText = "select name from names where name =@name";
            myCommand.Parameters.AddWithValue("@name", nameFilter);
            SqlDataReader myReader = myCommand.ExecuteReader();

            while(myReader.Read())
            {
                if(result.Length > 0)
                {
                    result += "#";
                }
                result += myReader["name"].ToString();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            myConnection.Close();
        }

        return result;
    }
}

编辑

我更喜欢不同的方法:

public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    public String[] getData(string nameFilter)
    {
        var names = new List<string>();
        SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
        try
        {
            myConnection.Open();

            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandText = "select name from names where name = @name";
            myCommand.Parameters.AddWithValue("@name", nameFilter);
            SqlDataReader myReader = myCommand.ExecuteReader();

            while(myReader.Read())
            {
                names.Add(myReader["name"].ToString());
            }
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.Message);
        }
        finally
        {
            myConnection.Close();
        }

        return names.ToArray();
    }
}

【讨论】:

  • @Emo :非常感谢您的编辑和代码。我试过了..但是当我点击浏览器中的调用按钮时,我得到了这个 [tempuri.org/"/>] ..没有显示字符串数组..
  • @Emo :是的,你最近编辑的代码运行良好..但我只想在它从我的数据库中获取每条记录后插入一个分隔符......例如:john#ann#joe
  • @Parth_90:我添加了分隔符。如果您希望有很多名称,最好在附加名称时切换回字符串数组或 StringBuilder。
  • 嘿,谢谢!实际上我没有很多名字要获取..所以只会使用这个。感谢所有的帮助! :-)
  • @Parth_90:没问题,很乐意提供帮助。一点建议:切换回(如果可能)返回一个字符串数组。这更容易,更不容易出错(如果名称包含#
【解决方案2】:
 [WebMethod]
    public string getData()//changed to return string
    {

        SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
        try
        {
            myConnection.Open();

            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandText = "select name from names";//you can make it select distinct

            SqlDataReader myReader = myCommand.ExecuteReader();
            string toReturn = "";
            while(myReader.Read())
            {
                if (myReader.Read())
                {
                     toReturn += myReader["name"].ToString() + "#";
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            myConnection.Close();
        }

        return toReturn; //# as delimiter
    }

【讨论】:

    【解决方案3】:

    首先,您的查询只返回数字而不是一组行。所以你应该像这样使用sql:

    select name from names
    

    其次,要返回数组,您可以使用 List 而不是预定义的数组: 我将使用以下方法:

    var result = new List<string>();
    while(myReader.Read())
    {
      result.Add(reader["name"].ToString() + "#");
    }
    
    return result.ToArray();
    

    或者如果你想返回一个字符串:

    return string.Join("#", result.ToArray())
    

    【讨论】:

    • 是的,我遵循您的方法,是的,这是一种比我更好的方法。因为我特别是 C# 新手,所以我需要一些时间。但只要像你这样的人帮助我更好地理解事物,我觉得我会很快学到东西:-)
    猜你喜欢
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2018-12-22
    • 2014-11-15
    • 1970-01-01
    相关资源
    最近更新 更多