我有一个行为路由,返回非实体集合。
ActionConfiguration previewInvoices = this.EntityType.Collection.Action("PreviewInvoices");
previewInvoices.ReturnsCollection<InvoicePreviewComponent>();
现在当我查询以获得结果时,我使用$take=20
来控制通过javascript进行分页。但是,它不会像使用$inlinecount=allpages
的实体集一样返回计数。
我一直在做的一个解决方案是将行改为:
ActionConfiguration previewInvoices = this.EntityType.Collection.Action("PreviewInvoices");
previewInvoices.ReturnsCollectionFromCollection<InvoicePreviewComponent>("InvoicePreviewComponent");
然而,这会在$metadata
中生成ghost实体集,我用它来生成javascript模型和请求。不理想,最终不能正确地将其注释为实体集。
如何修改响应JSON格式化程序以按要求提供计数?
答案 0 :(得分:1)
非实体集合的计数值不会被序列化到响应正文中。
但您可以通过以下代码获取计数值:
response.RequestMessage.ODataProperties().TotalCount
(注意:ODataProperties()是静态类中的扩展方法 System.Web.Http.OData.Extensions.HttpRequestMessageExtensions)
答案 1 :(得分:0)
这也可以通过动作过滤器来实现:
/// <summary>
/// Use this attribute whenever total number of records needs to be returned in the response in order to perform paging related operations at client side.
/// </summary>
public class PagedResultAttribute: ActionFilterAttribute
{
/// <summary>
///
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
if (actionExecutedContext.Response != null&& actionExecutedContext.Response.StatusCode==System.Net.HttpStatusCode.OK)
{
dynamic responseContent=null;
if (actionExecutedContext.Response.Content != null)
responseContent = actionExecutedContext.Response.Content.ReadAsAsync<dynamic>().Result;
var count = actionExecutedContext.Response.RequestMessage.ODataProperties().TotalCount;
var res = new PageResult<dynamic>() {TotalCount=count,Items= responseContent };
HttpResponseMessage message = new HttpResponseMessage();
message.StatusCode = actionExecutedContext.Response.StatusCode;
var strMessage = new StringContent(JsonConvert.SerializeObject(res), Encoding.UTF8, "application/json");
message.Content = strMessage;
actionExecutedContext.Response = message;
}
}
}
自定义PageResult类是:
public class PageResult<T>
{
public long? TotalCount { get; set; }
public T Items { get; set; }
}
用法:
[PagedResult]
[EnableQuery()]