WebApi - Binding to Header Values

We have a WebApi project at work where we need to get a value from the header and use it as input to a query.

One way to do this is

1
2
3
4
5
public IActionResult DoSomething()
{
var headerValues = request.Headers.GetValues("MyHeader");
var header = headerValues.FirstOrDefault();
}

YUCK.

I wasn’t very keen on this and starting think it must be possible to use WebApi’s model binding. After a bit of searching I found https://blog.bennymichielsen.be/2013/11/17/modelbinding-with-headers-in-asp-net-webapi/ which gave me most of
the details. This left me with model binding working, but not quite in the way I wanted.

1
2
3
4
public IActionResult DoSomething([ValueProvider(typeof(HeaderValue))] int custId)
{
//Do something with custId
}

Better, but not quite what I wanted.

In trying to fill in a few of the missing pieces I had a look at the WebApi code on GitHub and found that in one of their Integration tests Microsoft had pretty much exactly what I was after.

So between the two I was able to put together something I was happy with.

1
2
3
4
5
6
7
8
9
10
11
12
public class HeaderValueProviderFactory : ValueProviderFactory
{
/// <summary>
/// Gets the value provider.
/// </summary>
/// <param name="actionContext">The action context.</param>
/// <returns></returns>
public override IValueProvider GetValueProvider(HttpActionContext actionContext)
{
return new HeaderValueProvider(actionContext.Request);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/// <summary>
/// Returns the tenant id from the request header.
/// http://blog.bennymichielsen.be/2013/11/17/modelbinding-with-headers-in-asp-net-webapi/
/// also some ideas from the ASP.NET unit tests
/// https://github.com/ASP-NET-MVC/aspnetwebstack/blob/4e40cdef9c8a8226685f95ef03b746bc8322aa92/test/System.Web.Http.Integration.Test/ModelBinding/ModelBindingController.cs#L271
/// </summary>
public class HeaderValueProvider : IValueProvider
{
private readonly HttpRequestMessage _requestMessage;

/// <summary>
/// Initializes a new instance of the <see cref="HeaderValueProvider"/> class.
/// </summary>
/// <param name="requestMessage">The request message.</param>
public HeaderValueProvider(HttpRequestMessage requestMessage)
{
_requestMessage = requestMessage;
}

/// <summary>
/// Determines whether the specified prefix contains prefix.
/// </summary>
/// <param name="prefix">The prefix.</param>
/// <returns></returns>
public bool ContainsPrefix(string prefix)
{
return _requestMessage.Headers.Contains(prefix);
}

/// <summary>
/// Gets the value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public ValueProviderResult GetValue(string key)
{
IEnumerable<string> headerValue;
ValueProviderResult result = null;
if (_requestMessage.Headers.TryGetValues(key, out headerValue))
{
var header = headerValue as IList<string> ?? headerValue.ToList();
if (header.Any())
{
var value = header.First();
result = new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
}
}
return result;

}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
public class FromHeaderAttribute : ModelBinderAttribute
{
/// <summary>
/// Gets the value providers that will be fed to the model binder.
/// </summary>
/// <returns>
/// A collection of <see cref="T:System.Web.Http.ValueProviders.ValueProviderFactory"/> instances.
/// </returns>
/// <param name="configuration">The <see cref="T:System.Web.Http.HttpConfiguration"/> configuration object.</param>
public override IEnumerable<ValueProviderFactory> GetValueProviderFactories(HttpConfiguration configuration)
{
return base.GetValueProviderFactories(configuration).OfType<HeaderValueProviderFactory>();
}
}
1
2
3
4
5
6
7
8
 public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Services.Add(typeof(ValueProviderFactory), new HeaderValueProviderFactory());
}
}

So finally I can just do

1
2
3
4
public IActionResult DoSomething([FromHeader(Name="CustId")] int custId)
{
// Do something with custId
}

Much nicer.