如何在Web API的请求标头中添加新的键值对?

时间:2014-08-25 05:57:16

标签: c# asp.net-web-api2

我的api调用代码与此类似

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:56851/");

//Here I want add Authentication Header as new key value pair 
//Something similar like this 
//client.Headers["AuthenticationToken"]="FASFASFA#$";

        var id = txtSearch.Text.Trim();
        var url = "api/User/" + id;
        HttpResponseMessage response = client.GetAsync(url).Result;
        if (response.IsSuccessStatusCode)
        {
            var users = response.Content.ReadAsAsync<Users>().Result;

            MessageBox.Show("User Found : " + 
            users.FirstName + " "  + users.LastName);
        }

如何在Web API的请求标头中添加新的键值对?

1 个答案:

答案 0 :(得分:0)

您可以使用HttpClient的{​​{3}}属性:

client.DefaultRequestHeaders.Authorization = 
          new AuthenticationHeaderValue("YourAuthenticationScheme", "FASFASFA#$");