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 | public IActionResult DoSomething() |
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 | public IActionResult DoSomething([ValueProvider(typeof(HeaderValue))] int 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 | public class HeaderValueProviderFactory : ValueProviderFactory |
1 | /// <summary> |
1 | [ ] |
1 | public static class WebApiConfig |
So finally I can just do
1 | public IActionResult DoSomething([FromHeader(Name="CustId")] int custId) |
Much nicer.