Items count in OData v4 WebAPI response

前端 未结 4 1819
野性不改
野性不改 2021-02-14 03:47

How to return number of items in OData v4 HTTP response?

I need this number to pagination, so it should be number of items after filtering, but before \'skip\' and \'top

4条回答
  •  别那么骄傲
    2021-02-14 04:10

    This can also be achieved by an action filter:

    /// 
    /// 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.
    /// 
    public class PagedResultAttribute: ActionFilterAttribute
    {
        /// 
        /// 
        /// 
        /// 
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            if (actionExecutedContext.Response != null)
            {                
                dynamic responseContent=null;
                if (actionExecutedContext.Response.Content != null)
                    responseContent = actionExecutedContext.Response.Content.ReadAsAsync().Result;
                var count = actionExecutedContext.Response.RequestMessage.ODataProperties().TotalCount;
                var res = new PageResult() {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;               
            }           
        }
    }
    

    And the custom PageResult class is:

    public class PageResult
    {      
        public long? TotalCount { get; set; }
        public T Items { get; set; }
    }
    

    Usage:

    [PagedResult]
    [EnableQuery()]  
    

提交回复
热议问题