33
votes

I am trying to create a custom filter in asp net core web api which is as below but unable to get header info.

internal class BasicAuthFilterAttribute : ActionFilterAttribute
{
  private StringValues xyz;

  public override void OnActionExecuting(ActionExecutingContext actionContext)
  {
    var authHeader = actionContext.HttpContext.Request.Headers.TryGetValue("Basic", out xyz);           
  }
}

TryGetValue always return false however I can see Headers contains the "Basic" header. As I am new in ASP.NET Core so can anyone guide me what I am possibly doing wrong?

Here how headers looks like. enter image description here

4
May be you should check "Basic" in keys, not in values? - Aleksej Vasinov
@AleksejVasinov Thanks, You are right key should be "Authorization" not "Basic". - Jyotish Singh
The left side is the key and the right side is the value. - Joel Harkes

4 Answers

53
votes

Thank you all for your valuable input however below code worked as expected.

actionContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationToken);
3
votes
public static class HttpRequestExtension
{
    public static string GetHeader(this HttpRequest request, string key)
    {
        return request.Headers.FirstOrDefault(x => x.Key == key).Value.FirstOrDefault();
    }
}

calling method:

 var Authorization = Request.GetHeader("Authorization");
1
votes
var xyz = context.HttpContext.Request?.Headers["Basic"];
1
votes

How about this one? We shoule embrace the new variables. :)

bool tryGetValue = actionContext.ActionArguments.TryGetValue("data", out data);