42

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

3
  • 1
    May be you should check "Basic" in keys, not in values? Commented Feb 21, 2017 at 8:21
  • @AleksejVasinov Thanks, You are right key should be "Authorization" not "Basic". Commented Feb 21, 2017 at 8:36
  • The left side is the key and the right side is the value. Commented Feb 21, 2017 at 9:45

4 Answers 4

64

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

actionContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationToken);
Sign up to request clarification or add additional context in comments.

2 Comments

If you use C# 7, you can skip declaring the variable: actionContext HttpContext.Request.Headers.TryGetValue("Authorization", out var unittId);
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)
4
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 Comment

Be careful, when using First or Single linq methods to check to if the header key if it's case-sensitive. TryGetValue is not case-sensitive when checking the key.
2

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

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

Comments

0
var xyz = context.HttpContext.Request?.Headers["Basic"];

1 Comment

This is not correct. Header should be Authorization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.