首页 > 解决方案 > 使用 JSON 对 WCF 服务进行分页

问题描述

我制作了一个向某个客户端发送 JSON 字符串的 WCF 服务。我被要求进行某种分页,这样它就不会一次发送所有数据,但我不确定如何最好地进行此操作。到目前为止,我在网上阅读的内容似乎很模糊,或者并不真正适用于我的特定应用程序,至少不是以我理解的方式。

这是我的 WCF 的工作方式:

有一个 IService1:

        [OperationContract()]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, UriTemplate = "/BP?vCaseNr={vCaseNr}")]
    Stream BoligPraesentation(string vCaseNr);

服务1:

public Stream BoligPraesentation(string vSagsNr)
{
 SqlConnection con = new SqlConnection();
 con = Database();

 SqlDataAdapter dau = new SqlDataAdapter(*long sql here*, con);

 DataTable dtu = new DataTable();
 dau.Fill(dtu);
 string json = GetJson(dtu)

            if (json != "[]")
            {
                json = json.Replace("[", "");
                json = json.Replace("]", "");
                json = "{\"Things\": [" + json + "]}";
            }

 WebOperationContext.Current.OutgoingResponse.ContentType = 
 "application/json; charset=utf-8";
 return new MemoryStream(Encoding.UTF8.GetBytes(json));
}

GetJSon 看起来像这样:

private string GetJson(DataTable dt)
    {
        System.Web.Script.Serialization.JavaScriptSerializer Jserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rowsList = new List<Dictionary<string, object>>();
        Dictionary<string, object> row = null;

        foreach (DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }

            rowsList.Add(row);
        }

        return Jserializer.Serialize(rowsList);
    }

返回后的 JSON 看起来有点像这样:

{"Things": [{"CaseNr":6,"Titel":"some place V","Areal":null,"Adresse1":"Hsome address","Rum":2,"Etage":0,"PostNr":"9999","ByNavn":"city","EjendomNavn":"name here","Status":"LEDIG","Leje":"343434","AntalBilleder":0,"AntalProspekter":0,"AntalKort":0,"AntalTegninger":0},{"CaseNr":4,"Titel":"big place","Areal":null,"Adresse1":"adress 555","Rum":null,"Etage":3,"PostNr":"2222","ByNavn":"Germacity","EjendomNavn":"HSbuilding ApS","Status":"OPTAGET","Leje":"0.00","AntalBilleder":0,"AntalProspekter":0,"AntalKort":0,"AntalTegninger":0}

我不想同时发送所有东西(可能比我展示的两个多),我想一次发送 20 个,或者让客户决定多少。不过,我完全不确定如何进行这项工作,有什么建议吗?

PS:如果我需要显示更多信息,请说。

标签: c#jsonwcfpagination

解决方案


以下是分页需要遵循的通用步骤。

  1. 在客户端将发出的请求中获取pageNumberand pageSize(表示单个页面中的对象数,在您的情况下为 20)。
  2. 在您*long sql*使用这些数字来过滤结果并因此获得page. 使用 LINQ 的示例如下所示:var requestedPage = dbEntities.Skip(pageNumber*pageSize).Take(pageSize)
  3. 将这样的页面转换为JSON您需要的格式(流?)并返回。

pageNumber,pageSizetotal(表中所有实体的数量)连同page. 这将只是请求next或客户端previous的逻辑any page

这是我上面提到的LINQ 和分页的更多变体


推荐阅读