使用IHttpActionResult时如何设置自定义标题?

时间:2014-01-29 19:07:17

标签: c# asp.net asp.net-web-api

在ASP.NET Web API 2中,IHttpActionResult在简化控制器代码方面提供了很多价值,我不愿意停止使用它,但我遇到了问题。

我需要在传出响应上设置ETag,而我找不到任何可以访问响应标头的属性。目前我正在使用Ok<T>(T content)中的ApiController辅助方法,该方法返回OkNegotiatedContentResult<T>个对象。这似乎没有任何暴露,这让我可以修改标题。

我是否遗漏了某些内容,或者在使用库存IHttpActionResult类型时是否真的无法做到这一点?我考虑过一个消息处理程序,但后来我必须弄清楚如何将ETag从动作中传出(对于不同的动作,ETag的生成方式不同,因此不是为所有动作制作通用处理程序的问题。) / p>

我想避免使用原始的HttpResponseMessage,但目前看起来很难。

7 个答案:

答案 0 :(得分:33)

对于您的方案,您需要创建自定义IHttpActionResult。以下是我在运行OkNegotiatedContentResult<T>时从Content-Negotiation派生并设置Ok状态代码的示例。

public class CustomOkResult<T> : OkNegotiatedContentResult<T>
{
    public CustomOkResult(T content, ApiController controller)
        : base(content, controller) { }

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

    public string ETagValue { get; set; }

    public override async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.ExecuteAsync(cancellationToken);

        response.Headers.ETag = new EntityTagHeaderValue(this.ETagValue);

        return response;
    }        
}

控制器

public class ValuesController : ApiController
{
    public IHttpActionResult Get()
    {
        return new CustomOkResult<string>(content: "Hello World!", controller: this)
            {
                    ETagValue = "You ETag value"
            };
    }
}

请注意,您也可以从NegotiatedContentResult<T>派生,在这种情况下,您需要自己提供StatusCode。希望这会有所帮助。

您可以找到 OkNegotiatedContentResult<T> NegotiatedContentResult<T> 的源代码,您可以想象其实很简单。

答案 1 :(得分:29)

您可以创建HttpResponseMessage,根据需要添加标题,然后从中创建ResponseMessageResult

HttpResponseMessage response =new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("MyHeader", "MyHeaderValue");
return ResponseMessage(response);

答案 2 :(得分:8)

这是我没有ActionFilterAttributes的简单实现,类似于AlexACD的响应。我的解决方案使用ResponseMessageResult来实现IHttpActionResult接口。

HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
responseMessage.Headers.Add("Headername", "Value");
ResponseMessageResult response = new ResponseMessageResult(responseMessage);
return response;

答案 3 :(得分:5)

public static class HttpExtentions
{
    public static IHttpActionResult AddHeader(this IHttpActionResult action,
        string headerName, IEnumerable<string> headerValues)
    {
        return new HeaderActionResult(action, headerName, headerValues);
    }

    public static IHttpActionResult AddHeader(this IHttpActionResult action,
        string headerName, string header)
    {
        return AddHeader(action, headerName, new[] {header});
    }

    private class HeaderActionResult : IHttpActionResult
    {
        private readonly IHttpActionResult action;

        private readonly Tuple<string, IEnumerable<string>> header;

        public HeaderActionResult(IHttpActionResult action, string headerName,
            IEnumerable<string> headerValues)
        {
            this.action = action;

            header = Tuple.Create(headerName, headerValues);
        }

        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = await action.ExecuteAsync(cancellationToken);

            response.Headers.Add(header.Item1, header.Item2);

            return response;
        }
    }
}

答案 4 :(得分:3)

这可以通过ActionFilterAttribute来实现,它会在控制器函数之后检查响应但在它出去之前,然后你可以在控制器方法上设置属性来添加这些信息,这里是我的实现如下:

public class EnableETag : ActionFilterAttribute
{

    /// <summary>
    /// NOTE: a real production situation, especially when it involves a web garden
    ///       or a web farm deployment, the tags must be retrieved from the database or some other place common to all servers.
    /// </summary>
    private static ConcurrentDictionary<string, EntityTagHeaderValue> etags = new ConcurrentDictionary<string, EntityTagHeaderValue>();

    public override void OnActionExecuting(HttpActionContext context)
    {
        var request = context.Request;
        if (request.Method == HttpMethod.Get)
        {
            var key = GetKey(request);
            ICollection<EntityTagHeaderValue> etagsFromClient = request.Headers.IfNoneMatch;
            if (etagsFromClient.Count > 0)
            {
                EntityTagHeaderValue etag = null;
                if (etags.TryGetValue(key, out etag) && etagsFromClient.Any(t => t.Tag == etag.Tag))
                {
                    context.Response = new HttpResponseMessage(HttpStatusCode.NotModified);
                    SetCacheControl(context.Response);
                }
            }
        }
    }
    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        var request = context.Request;
        var key = GetKey(request);
        EntityTagHeaderValue etag;
        if (!etags.TryGetValue(key, out etag) || request.Method == HttpMethod.Put ||
        request.Method == HttpMethod.Post)
        {
            etag = new EntityTagHeaderValue("\"" + Guid.NewGuid().ToString() + "\"");
            etags.AddOrUpdate(key, etag, (k, val) => etag);
        }
        context.Response.Headers.ETag = etag;
        SetCacheControl(context.Response);
    }
    private string GetKey(HttpRequestMessage request)
    {
        return request.RequestUri.ToString();
    }

    /// <summary>
    /// Defines the time period to hold item in cache (currently 10 seconds)
    /// </summary>
    /// <param name="response"></param>
    private void SetCacheControl(HttpResponseMessage response)
    {
        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            MaxAge = TimeSpan.FromSeconds(10),
            MustRevalidate = true,
            Private = true
        };
    }
}

}

答案 5 :(得分:3)

以下是我在常用Web API 2库代码中使用的解决方案,可以轻松支持设置任何标头 - 或HttpResponseMessage中提供的ExecuteAsync上的任何其他属性 - 而不受限制任何特定的派生NegotiatedContentResult实施:

public class FlexibleNegotiatedContentResult<T> : NegotiatedContentResult<T>
{
    private readonly Action<HttpResponseMessage> _responseMessageDelegate;

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

    public FlexibleNegotiatedContentResult(HttpStatusCode statusCode, T content, ApiController controller, Action<HttpResponseMessage> responseMessageDelegate = null)
        : base(statusCode, content, controller)
    {
        _responseMessageDelegate = responseMessageDelegate;
    }

    public override async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage responseMessage = await base.ExecuteAsync(cancellationToken);

        if (_responseMessageDelegate != null)
        {
            _responseMessageDelegate(responseMessage);
        }

        return responseMessage;
    }
}

以及示例用法:

new FlexibleNegotiatedContentResult<string>(HttpStatusCode.Created, "Entity created!", controller, response => response.Headers.Location = new Uri("https://myapp.com/api/entity/1"));

答案 6 :(得分:1)

非常老的问题。也许其他答案在当时是有意义的,但是今天您只需添加此行即可,而无需更改或扩展IHttpActionResult。它完美地在响应中添加了标头。确保还按照以下格式格式化为RFC 1123标准。否则,尽管标题中显示了Last-Modified,但客户端无法使用HttpClient读取它。

    System.Web.HttpContext.Current.Response.Headers.
Add(Microsoft.Net.Http.Headers.HeaderNames.LastModified, DBdateModified.Value.ToString("r"));