Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Web API的请求头中添加新的键值对?_C#_Asp.net Web Api2 - Fatal编程技术网

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

C# 如何在Web API的请求头中添加新的键值对?,c#,asp.net-web-api2,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["Authenticati

我的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的请求头中添加新的键值对?

您可以使用HttpClient的属性:

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