Jyotish Singh
Jyotish Singh

Reputation: 2115

Unable to get request header in asp net core web API

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

Upvotes: 42

Views: 102356

Answers (4)

impotunator
impotunator

Reputation: 41

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");

Upvotes: 4

Foyzul Karim
Foyzul Karim

Reputation: 4492

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

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

Upvotes: 2

ben yip
ben yip

Reputation: 117

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

Upvotes: 0

Jyotish Singh
Jyotish Singh

Reputation: 2115

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

actionContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationToken);

Upvotes: 64

Related Questions