How to extract custom header value in Web API mess

2019-01-08 04:57发布

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
}

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:

Cannot apply indexing with [] to an expression of type 'System.Net.Http.Headers.HttpRequestHeaders'

How can I access a single custom request header via the HttpRequestMessage (MSDN Documentation) instance passed into this overridden method?

9条回答
我命由我不由天
2楼-- · 2019-01-08 05:10

Create a new method - 'Returns an individual HTTP Header value' and call this method with key value everytime when you need to access multiple key Values from HttpRequestMessage.

public static string GetHeader(this HttpRequestMessage request, string key)
        {
            IEnumerable<string> keys = null;
            if (!request.Headers.TryGetValues(key, out keys))
                return null;

            return keys.First();
        }
查看更多
Bombasti
3楼-- · 2019-01-08 05:17

For ASP.NET you can get the header directly from parameter in controller method using this simple library/package. It provides a [FromHeader] attribute just like you have in ASP.NET Core :). For example:

    ...
    using RazHeaderAttribute.Attributes;

    [Route("api/{controller}")]
    public class RandomController : ApiController 
    {
        ...
        // GET api/random
        [HttpGet]
        public IEnumerable<string> Get([FromHeader("pages")] int page, [FromHeader] string rows)
        {
            // Print in the debug window to be sure our bound stuff are passed :)
            Debug.WriteLine($"Rows {rows}, Page {page}");
            ...
        }
    }
查看更多
祖国的老花朵
4楼-- · 2019-01-08 05:20

Try something like this:

IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();

There's also a TryGetValues method on Headers you can use if you're not always guaranteed to have access to the header.

查看更多
甜甜的少女心
5楼-- · 2019-01-08 05:22

One line solution

var id = request.Headers.GetValues("MyCustomID").FirstOrDefault();
查看更多
闹够了就滚
6楼-- · 2019-01-08 05:29

For ASP.Net Core there is an easy solution if want to use the param directly in the controller method: Use the [FromHeader] annotation.

        public JsonResult SendAsync([FromHeader] string myParam)
        {
        if(myParam == null)  //Param not set in request header
        {
           return null;
        }
        return doSomething();
    }   

Additional Info: In my case the "myParam" had to be a string, int was always 0.

查看更多
淡お忘
7楼-- · 2019-01-08 05:29
request.Headers.FirstOrDefault( x => x.Key == "MyCustomID" ).Value?.FirstOrDefault()

modern variant :)

查看更多
登录 后发表回答