I was looking for a way to get the header from a Web API request. After trying multiple things I ended up with creating my own model binder:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class OrdersController : ApiController | |
{ | |
public async Task<IList<Order>> GetOrders([FromHeader("X-Correlation-ID")] Guid correlationId) | |
{ | |
//Removed other code | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FromHeaderAttribute : ParameterBindingAttribute | |
{ | |
private string name; | |
public FromHeaderAttribute(string headerName) | |
{ | |
this.name = headerName; | |
} | |
public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter) | |
{ | |
return new FromHeaderBinding(parameter, this.name); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FromHeaderBinding : HttpParameterBinding | |
{ | |
private readonly string _name; | |
public FromHeaderBinding(HttpParameterDescriptor parameter, string headerName) | |
: base(parameter) | |
{ | |
if (string.IsNullOrEmpty(headerName)) throw new ArgumentNullException("headerName"); | |
_name = headerName; | |
} | |
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) | |
{ | |
IEnumerable<string> values; | |
if (actionContext.Request.Headers.TryGetValues(_name, out values)) | |
{ | |
var tempVal = values.FirstOrDefault(); | |
if (tempVal != null) | |
{ | |
var actionValue = Convert.ChangeType(tempVal, Descriptor.ParameterType); | |
actionContext.ActionArguments[Descriptor.ParameterName] = actionValue; | |
} | |
} | |
var taskSource = new TaskCompletionSource<object>(); | |
taskSource.SetResult(null); | |
return taskSource.Task; | |
} | |
} | |