30

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

Jyotish Singh
  • 1,763
  • 1
  • 15
  • 25

4 Answers4

50

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

actionContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationToken);
Irvin Dominin
  • 29,799
  • 9
  • 75
  • 107
Jyotish Singh
  • 1,763
  • 1
  • 15
  • 25
  • 17
    If you use C# 7, you can skip declaring the variable: actionContext HttpContext.Request.Headers.TryGetValue("Authorization", out var unittId); – AFD May 12 '17 at 10:58
  • If checking for empty values consider that a `StringValues` object is returned, and, though it has implicit type conversion, it is required to use e.g. `if (authorization == StringValues.Empty)` – conceptdeluxe Jul 30 '20 at 15:33
2
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");
Moddasir
  • 1,323
  • 12
  • 26
1
var xyz = context.HttpContext.Request?.Headers["Basic"];
Irvin Dominin
  • 29,799
  • 9
  • 75
  • 107
ben yip
  • 119
  • 1
  • 6
1

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

bool tryGetValue = actionContext.ActionArguments.TryGetValue("data", out data);
Foyzul Karim
  • 3,644
  • 5
  • 43
  • 68