Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 280
Jyotish Singh Avatar asked Feb 21 '17 08:02

Jyotish Singh


People also ask

How do I get request headers in .NET core?

You can use the [FromHeader] attribute to automatically map request headers to parameters (or model properties). It maps them by matching the request header key with the parameter name. Now send a request with a header: GET /movie/ TestId: 2022 ..

How do I add a header in web API?

Adding Custom Header for Individual Response We create a very basic HTTP GET endpoint. Within this endpoint, we access the Response object through the HttpContext object. Then, we add a new header, with the name of x-my-custom-header and a value of individual response .

How do I get custom header values in net core API?

Using IHTTPContextAccessor to extract custom header The above–discussed HttpContext or Request class gives us access to metadata including headers of given HttpContext within Controller. However, if you need to access headers or any HttpContext metadata in other services or modules then please use IHTTPContextAccessor.


Video Answer


3 Answers

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

actionContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationToken);
like image 149
Jyotish Singh Avatar answered Oct 19 '22 01:10

Jyotish Singh


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");
like image 3
impotunator Avatar answered Oct 19 '22 01:10

impotunator


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

bool tryGetValue = actionContext.ActionArguments.TryGetValue("data", out data);
like image 2
Foyzul Karim Avatar answered Oct 19 '22 01:10

Foyzul Karim