I need to allow a custom header called "secretToken". And every call to my webapi, the user should pass this header.
I searched for a way to do that, but I could not found an easy way. How can I allow this custom header?
I need to allow a custom header called "secretToken". And every call to my webapi, the user should pass this header.
I searched for a way to do that, but I could not found an easy way. How can I allow this custom header?
You mentioned 'allow' means passing from client? Which client?
If JavaScript, you can do something like this.
$.ajax({
type: 'GET',
url: '/api/values',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: { 'X-My-Secret-Token': 'Token' },
success: function (data) {
}
});
If .NET client, you can do something like this.
string url = "http://www.myurl/api/values";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-My-Secret-Token", "Token");
var message = client.GetAsync(url).Result;
In Web API, you can read the header in HttpRequestMessage object from any component in the pipeline. For example, you can read the header from a handler like this.
public class MyHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var headers = request.Headers;
if (headers.Contains("X-My-Secret-Token"))
{
string token = headers.GetValues("X-My-Secret-Token").First();
}
}
}