正如评论中所建议的,您可以创建一个 ActionFilterAttribute。这是一个仅处理 MaxAge 属性的简单示例:
public class CacheControlAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public int MaxAge { get; set; }
public CacheControlAttribute()
{
MaxAge = 3600;
}
public override void OnActionExecuted(HttpActionExecutedContext context)
{
if (context.Response != null)
context.Response.Headers.CacheControl = new CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromSeconds(MaxAge)
};
base.OnActionExecuted(context);
}
}
然后你可以将它应用到你的方法中:
[CacheControl(MaxAge = 60)]
public string GetFoo(int id)
{
// ...
}