问题描述
我目前在我的 Web API 服务中有一个消息处理程序,它覆盖SendAsync",如下所示:
I currently have a message handler in my Web API service that overrides 'SendAsync' as follows:
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//implementation
}
在此代码中,我需要检查名为 MyCustomID
的自定义添加的请求标头值.问题是当我执行以下操作时:
Within this code I need to inspect a custom added request header value named MyCustomID
. The problem is when I do the following:
if (request.Headers.Contains("MyCustomID")) //OK
var id = request.Headers["MyCustomID"]; //build error - not OK
...我收到以下错误消息:
...I get the following error message:
不能将带有 [] 的索引应用于类型表达式'System.Net.Http.Headers.HttpRequestHeaders'
如何通过 HttpRequestMessage
(MSDN 文档) 实例传递到这个重写的方法?
How can I access a single custom request header via the HttpRequestMessage
(MSDN Documentation) instance passed into this overridden method?
推荐答案
试试这个:
IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();
如果您不能总是保证可以访问标头,则可以使用标头上的 TryGetValues 方法.
There's also a TryGetValues method on Headers you can use if you're not always guaranteed to have access to the header.
这篇关于如何在 Web API 消息处理程序中提取自定义标头值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!