【问题标题】:web service page System.IndexOutOfRangeExceptionWeb 服务页面 System.IndexOutOfRangeException
【发布时间】:2015-05-29 18:08:01
【问题描述】:
public class GetAreaFromCity : System.Web.Services.WebService
{
    [WebMethod]
    public GetAreaByCityId ClassForGetCIty(int City_Id)
    {
        string CS =ConfigurationManager.ConnectionStrings["FOODINNConnectionString"].ConnectionString;

        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("spGetCityById",con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter parameter = new SqlParameter("@ID", City_Id);

            //To assiate this parameter object with cmd object
            cmd.Parameters.Add(parameter);
            GetAreaByCityId GETAreaByCityId =new GetAreaByCityId();
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            //as WeakReference read data wewant ToString retrive Column value & then polute this property City_Id values
            while (reader.Read()){
                GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);
                GETAreaByCityId.Area_Id =     Convert.ToInt32(reader["Area_Id"]);

            }
            return GETAreaByCityId;

            //ToString return sql
        }
    }
}

这是我的服务页面代码

public class GetAreaByCityId
{
    public int Ca_Id {get;set; }
    public int City_Id { get; set; }
    public int Area_Id { get; set; }
}

这是按城市获取区域的类

Create Proc [dbo].[spGetCityById]
@ID int 
as
Begin
Select Area_Id from 
CITIES_AREA where City_Id = @ID
End
GO

以上数据库程序是可以检索数据的

System.IndexOutOfRangeException: City_Id 在 System.Data.ProviderBase.FieldNameLookup.GetOrdinal(字符串字段名) 在 System.Data.SqlClient.SqlDataReader.GetOrdinal(字符串名称) 在 System.Data.SqlClient.SqlDataReader.get_Item(字符串名称) 在 c:\Users\Mudassir\Documents\Visual Studio 2013\Projects\WebApplication1\WebAppli 中的 WebApplication1.GetAreaFromCity.ClassForGetCIty(Int32 City_Id)

上面的错误我不知道是什么问题

【问题讨论】:

  • ASMX 是一项遗留技术,不应用于新开发。 WCF 或 ASP.NET Web API 应用于 Web 服务客户端和服务器的所有新开发。一个提示:微软已经在 MSDN 上停用了ASMX Forum

标签: asp.net asmx


【解决方案1】:

您的存储过程只返回Area_Id。您在“while 循环”while (reader.Read()){ 中的代码正在尝试从两列中读取数据:

  • City_Id
  • Area_Id

您可以将列 City_Id 添加到存储过程查询的结果集中,但您已经拥有该值,因为您将其作为参数传递给存储过程。

最简单的解决方法可能就是更改这一行:

GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);

到这里:

GETAreaByCityId.City_Id = City_Id;

【讨论】:

  • 我很高兴它成功了!如果您有机会请将我的答案标记为“已接受”,这将使您的声望提高 +2,如果您认为这代表“高质量”的答案,那么也请点赞。
猜你喜欢
  • 2023-03-18
  • 2010-12-04
  • 1970-01-01
  • 2011-07-06
  • 2012-02-15
  • 1970-01-01
  • 2017-03-05
  • 2013-03-20
  • 2011-01-03
相关资源
最近更新 更多