正在从web服务获取返回的列表

本文关键字:返回 列表 获取 服务 web | 更新日期: 2023-09-27 18:24:07

我编写了一个相当简单的web服务,它将SQL查询的结果集放入列表中。在我使用web服务的项目中,我在调用包含结果集的列表时遇到了问题。我将把我的代码放在下面:

Web服务

[OperationContract]
List<ViewDetails> ViewDetails();
[DataContract]
public class ViewDetails
{
    public string TitleView { get; set; }
    public string BodyView { get; set; }
    public string AuthorView { get; set; }
    public ViewDetails() { }
    public ViewDetails(string myTitleView, string myBodyView, string myAuthorView)
    {
        this.TitleView = myTitleView;
        this.BodyView = myBodyView;
        this.AuthorView = myAuthorView;
    }
}
 public List<ViewDetails> ViewDetails()
    {
        List<ViewDetails> details = new List<ViewDetails>();
        SqlConnection conn = new SqlConnection(strConnString);
        conn.Open();
        SqlCommand cmd = new SqlCommand("SELECT TOP 2 [My_Title] AS 'Title', [My_Body] AS 'Body', [My_Author] AS 'Author' FROM [My_table] ORDER BY [Date] DESC", conn);
        SqlDataReader rdrDetails = cmd.ExecuteReader();
        try
        {
            while (rdrDetails.Read())
            {
                details.Add(new ViewDetails(rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Title")).ToString(), rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Body")).ToString(), rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Author")).ToString()));
            }
        }
        catch (Exception e)
        {
            //exception
        }
        finally
        {
            conn.Close();
        }
        return details;
    }

我使用web服务的项目

 public async void ViewData()
 {
        ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
        string title = string.Empty;
        string body = string.Empty;
        string author = string.Empty;
        var res = await client.ViewDetailsAsync();
  }

我希望能够在我的ViewData类中做这样的事情,这样我就可以将结果存储在变量中,并将它们分配给textblocks,等等

title = res.TitleView;

但它不允许我……有人看到我缺少的东西吗?

注意:这是一个通用的Windows应用程序

正在从web服务获取返回的列表

您的ViewDetails数据协定属性中缺少DataMember属性。

[DataContract]
public class ViewDetails
{
   [DataMember]  
   public string TitleView { get; set; }
   [DataMember]
   public string BodyView { get; set; }
   [DataMember]
   public string AuthorView { get; set; }
    public ViewDetails() { }
    public ViewDetails(string myTitleView, string myBodyView, string myAuthorView)
    {
     this.TitleView = myTitleView;
     this.BodyView = myBodyView;
     this.AuthorView = myAuthorView;
    }
}

您遗漏了res就是List<ViewDetails>res不是ViewDetails的实例。因此,您应该键入title = res[0].TitleView;