1

嗨,我是 MVC4 的新手,我正在使用 asp.net mvc4 创建 RESTFUL WebAPI。
我的 api 返回一个 xml 字符串,如下所示:

<ArrayOfFacilities xmlns:xsd="http://www.w3.org/2001/XMLSchema"    
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Facilities>...</Facilities>
<Facilities>...</Facilities>
</ArrayOfFacilities>    

我想在上述节点之前添加一个节点来描述分页,例如

<wstxns1:pager>
<wstxns1:page>11</wstxns1:page>
<wstxns1:total>502</wstxns1:total>
<wstxns1:pageSize>50</wstxns1:pageSize>
<wstxns1:prevPage>http://apps.dhis2.org/dev/api/dataElements?page=10</wstxns1:prevPage>
<wstxns1:pageCount>11</wstxns1:pageCount>
</wstxns1:pager>

请帮忙,谢谢

4

1 回答 1

1
    public class AppendPagerHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return base.SendAsync(request, cancellationToken).ContinueWith(
                (task) =>
                {
                    HttpResponseMessage response = task.Result;
                    var xml = response.Content.ReadAsStringAsync().Result;
                    var newContents = xml.Substring(0, xml.IndexOf("ma\">")+4)+
                            @"<pager>
                                <page>11</page>
                                <total>502</total>
                                <pageSize>50</pageSize>
                                <prevPage>http://apps.dhis2.org/dev/api/dataElements?page=10</prevPage>
                                <pageCount>11</pageCount>
                          </pager>" + xml.Substring(xml.IndexOf("ma\">") + 4);
                    response.Content = new StringContent(newContents);
                    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/xml");
                    return response;
                }
            );
        }
    }
        GlobalConfiguration.Configuration.MessageHandlers.Add(new Mvc4WebApi.Controllers.ValuesController.AppendPagerHandler());

    public List<Facilities> Get()
    {
        var list = new List<Facilities>();
        list.Add(new Facilities { Name = "A" });
        list.Add(new Facilities { Name = "B" });
        return list;
    }
于 2012-05-22T09:33:57.453 回答