在ApiController中添加自定义响应标头 [英] Add a custom response header in ApiController
问题描述
直到现在,我有一个GET
方法,如下所示:
Until now, I had a GET
method that looked like the following:
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()
});
}
这就像一种魅力,很好.但是,最近我被告知发送响应元数据(即Total
,Count
和Last
属性)作为响应自定义标头,而不是响应正文.
This worked like a charm and it was good. However, I was told recently to send the response metadata (that is, Total
, Count
and Last
properties) as response custom headers instead of the response body.
我无法从ApiController访问Response
.我想到了过滤器或属性,但是如何获取元数据值?
I cannot manage to access the Response
from the ApiController. I thought of a filter or attribute, but how would I get the metadata values?
我可以将所有这些信息保留在响应中,然后有一个过滤器,该过滤器将在发送给客户端之前反序列化响应,并使用标头创建一个新的响应器,但这似乎很麻烦而且很糟糕.
I can keep all this information on the response and then have a filter that will deserialize the response before being sent to the client, and create a new one with the headers, but that seems troublesome and bad.
是否可以直接在ApiController
上通过此方法添加自定义标头?
Is there a way to add custom headers directly from this method on an ApiController
?
推荐答案
我已输入评论,这是我的完整答案.
I have entered comments, here is my complete answer.
您将需要创建一个自定义过滤器并将其应用于您的控制器.
You will need to create a custom filter and apply that to your controller .
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";
}
}
这篇关于在ApiController中添加自定义响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!