3

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?

2
  • allow means you want to check custom header of you are asking about passing from client Commented Jul 16, 2013 at 20:24
  • @Ajaybeniwal passing from client Commented Jul 16, 2013 at 20:43

2 Answers 2

6

There's one more thing in .config file:

    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,auth-key" />
        </customHeaders>
    </httpProtocol>
Sign up to request clarification or add additional context in comments.

Comments

5

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();
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.