How to Extract Custom Header Value in Web API Message Handler

How to extract custom header value?

Request.Headers returns Microsoft.AspNetCore.Http.IHeaderDictionary interface that define next property:

StringValues this[string key] { get; set; }

IHeaderDictionary has a different indexer contract than IDictionary, where it will return StringValues.Empty for missing entries.

Return type: Microsoft.Extensions.Primitives.StringValues

Returns: The stored value, or StringValues.Empty if the key is not present.

So, you can simply use Request.Headers["environment"] to get value of "environment" header

How to get header values in https calls in c#

To retrieve data from your Header You can use this Request.Headers, you will find an example below

var apiKey = Request.Headers.GetValues("apiKey")

Resquest From Postman

Resquest From Postman

Retrieve your data from header

Retrieve your data from header

Getting Header Values in WebApi 2 Controller

Try this

IEnumerable<string> headerValues;
var nameFilter= string.Empty;
if (Request.Headers.TryGetValues("sSearch_1", out headerValues))
{
nameFilter = headerValues.FirstOrDefault();
}

How to read a custom header in owin middleware?

Should be able to access headers via the request in the context.

For example

public class MyCustomMiddleware : OwinMiddleware {

public MyCustomMiddleware(OwinMiddleware next)
: base(next) {

}

public override async Task Invoke(IOwinContext context) {

var request = context.Request;
var headers = request.Headers;
var headerKey = "X-TYPE";
// custome header
if (headers.ContainsKey(headerKey)) {
var xType = headers[headerKey];
//...
}

// continue pipeline
await Next.Invoke(context);

//...
}
}


Related Topics



Leave a reply



Submit