c# - 使用 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:如果我需要显示更多信息,请说。
解决方案
以下是分页需要遵循的通用步骤。
- 在客户端将发出的请求中获取
pageNumber
andpageSize
(表示单个页面中的对象数,在您的情况下为 20)。 - 在您
*long sql*
使用这些数字来过滤结果并因此获得page
. 使用 LINQ 的示例如下所示:var requestedPage = dbEntities.Skip(pageNumber*pageSize).Take(pageSize)
- 将这样的页面转换为
JSON
您需要的格式(流?)并返回。
将pageNumber
,pageSize
和total
(表中所有实体的数量)连同page
. 这将只是请求next
或客户端previous
的逻辑any page
。
这是我上面提到的LINQ 和分页的更多变体
推荐阅读
- ruby-on-rails - Docker Compose 第 3 版:缓存 gem 以加快运行时捆绑安装
- python - 为什么 python 子模块没有出现在 dir(module) 的列表中?
- html - 搜索栏和搜索按钮的高度不同
- r - 在 Shiny 服务器上运行应用程序时,使用 GPU 的脚本会引发错误
- r - r中预测的贪婪特征选择
- excel - 如果我有 chart.xml 文件,有没有办法在 Excel 中创建图表?
- mysql - 使用 SQL 在一列上有多个名称
- c - 解析命令仅适用于单字命令
- c# - 为什么我需要一个 int 减去一个 char 才能得到正确的结果?C#
- php - 查找一个检查短代码是否存在于帖子中的过程:我的尝试中有问题