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.
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 ..
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 .
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.
Thank you all for your valuable input however below code worked as expected.
actionContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationToken);
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");
How about this one? We shoule embrace the new variables. :)
bool tryGetValue = actionContext.ActionArguments.TryGetValue("data", out data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With