gpt4 book ai didi

c# - Web API 2.0 IHttpActionResult 缓存

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:54 24 4
gpt4 key购买 nike

我正在使用此代码返回对象内容,但我想缓存添加 Cache-Control header 的响应。

[AllowAnonymous]
[Route("GetPublicContent")]
[HttpGet]
public IHttpActionResult GetPublicContent([FromUri]UpdateContentDto dto)
{

if (dto == null)
return BadRequest();

var content = _contentService.GetPublicContent(dto);
if (content == null)
return BadRequest();
return new Ok(content);

}

就是这样!谢谢!!

最佳答案

创建一个继承自 OkNegotiatedContentResult<T> 的新类:

public class CachedOkResult<T> : OkNegotiatedContentResult<T>
{
public CachedOkResult(T content, TimeSpan howLong, ApiController controller) : base(content, controller)
{
HowLong = howLong;
}

public CachedOkResult(T content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
: base(content, contentNegotiator, request, formatters) { }

public TimeSpan HowLong { get; private set; }


public override async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = await base.ExecuteAsync(cancellationToken);
response.Headers.CacheControl = new CacheControlHeaderValue() {
Public = false,
MaxAge = HowLong
};

return response;
}
}

要在您的 Controller 中使用它,只需返回 CachedOkResult 的一个新实例即可类:

public async Task<IHttpActionResult> GetSomething(string id)
{
var value = await GetAsyncResult(id);
// cache result for 60 seconds
return new CachedOkResult<string>(value, TimeSpan.FromSeconds(60), this);
}

标题将像这样通过电线:

Cache-Control:max-age=60
Content-Length:551
Content-Type:application/json; charset=utf-8
... other headers snipped ...

关于c# - Web API 2.0 IHttpActionResult 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29372710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com