到目前为止,我有一个GET方法,如下所示:

protected override async Task<IHttpActionResult> GetAll(QueryData query)
{
     // ... Some operations

     //LINQ Expression based on the query parameters
     Expression<Func<Entity, bool>> queryExpression = BuildQueryExpression(query);

     //Begin to count all the entities in the repository
     Task<int> countingEntities = repo.CountAsync(queryExpression);

     //Reads an entity that will be the page start
     Entity start = await repo.ReadAsync(query.Start);

     //Reads all the entities starting from the start entity
     IEnumerable<Entity> found = await repo.BrowseAllAsync(start, queryExpression);

     //Truncates to page size
     found = found.Take(query.Size);

     //Number of entities returned in response
     int count = found.Count();

     //Number of total entities (without pagination)
     int total = await countingEntities;

     return Ok(new {
          Total = total,
          Count = count,
          Last = count > 0 ? GetEntityKey(found.Last()) : default(Key),
          Data = found.Select(e => IsResourceOwner(e) ? MapToOwnerDTO(e) : MapToDTO(e)).ToList()
     });
}

这很有魅力,很好.然而,我最近被告知将响应metadata(即TotalCountLast属性)作为响应自定义头而不是响应体发送.

我无法从ApicController访问Response.我想到了一个过滤器或属性,但如何获取元数据值呢?

我可以在响应中保留所有这些信息,然后有一个过滤器,在发送到客户机之前将响应反序列化,并创建一个带有标题的新过滤器,但这似乎既麻烦又糟糕.

有没有办法直接从这个方法在ApiController上添加自定义标题?

推荐答案

我已经输入了 comments ,以下是我的完整答案.

您需要创建一个自定义过滤器,并将其应用于控制器.

public class CustomHeaderFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       var count = actionExecutedContext.Request.Properties["Count"];
       actionExecutedContext.Response.Content.Headers.Add("totalHeader", count);
    }
}

在你的控制器里

  public class AddressController : ApiController
        {
            public async Task<Address> Get()
            {
               Request.Properties["Count"] = "123";
            }
    }

Asp.net相关问答推荐

更新剃须刀页面中图表的值

在 Web.Config 中模拟标签

HttpRuntime.Cache[] 与 Application[]

SignalR 不在服务器上使用 Session

asp.net:与其中的用户控件相比,控件/页面的页面生命周期顺序是什么?

IIS 将旧用户名返回到我的应用程序

是否可以使用 Membership API 更改用户名

在程序集中找不到上下文类型

asp.net mvc 中的 RedirectToAction 用法

如何将 Web 应用程序项目转换为类库项目

HttpContext.Current.Cache.Insert 和 HttpContext.Current.Cache.Add 有什么区别

从命令行复制 VS2008发布网站

回发后 Document.Ready() 不起作用

如何获得 System.Diagnostics.Process 的输出?

如何在 ASP.NET 中通过 LAN 访问您的网站

Azure 网站 301 重定向 - 我应该把它放在哪里?

避免在 ASP.NET MVC 中使用会话状态是一种好习惯吗?如果是,为什么以及如何?

GZIP 与 DEFLATE 压缩相比有什么优势?

解耦 ASP.NET MVC 5 标识以允许实现分层应用程序

Application_End global.asax