Get request-header in web api

Matthias Burger picture Matthias Burger · Oct 7, 2016 · Viewed 8.2k times · Source

I'm trying to set a header with a simple key/value-pair and want to read this from my API. So this is my call from client:

public async Task<T> Auth_GetAsync<T>(string path)
{
    var client = BaseHttpClient;
    var request = new HttpRequestMessage
    {
        RequestUri = new Uri(Path.Combine(client.BaseAddress.AbsoluteUri, path)),
        Method = HttpMethod.Get,
        Headers = { {"key", "param"} }
    };
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(RequestHeader));
    var task = await client.SendAsync(request);
    return task.IsSuccessStatusCode
                    ? JsonConvert.DeserializeObject<T>(await task.Content.ReadAsStringAsync())
                    : default(T);
}

when I'm trying to read the header in my action, I get it completely (with my key/value-pair)

public async Task<IEnumerable<string>> GetAsync()
{
    var i = Request.Headers;
    return await Task.Run(() => new[] { "value1", "value2" });
}

when I'm trying to do this with the ActionFilterAttribute and/or the IAuthorizationFilter my header always contains other keys, but never contains my key/value-pair. This is my Attribute:

public class RequiresKeyAttribute : ActionFilterAttribute, IAuthorizationFilter
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var req = filterContext.HttpContext.Request;
        var auth = req.Headers["key"]; // this is null here
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var i = filterContext.HttpContext.Request.Headers;
    }
}

My target is, that the actionfilter checks whether the key is set in the header or not. I don't always want to check in my action if the key is set and validate it,...

Am I doing something wrong? Or is there solution to do this?

Answer

cuongle picture cuongle · Oct 7, 2016

Maybe you inherited the wrong ActionFilterAttribute which comes from MVC, not Web Api because WebApi uses HttpActionContext, not ActionExecutingContext like below:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    //code
}

You just use using System.Web.Http.Filters.ActionFilterAttribute from WebApi, it will be fine.