Reputation: 387
I'm trying to add a custom header to the request header of my web application. In my web application I'm retrieving data from a web API, in this request I want to add a custom header which contains the string sessionID
. I'm looking for a general solution so that I don't have to add the same code before every call I make.
My Controller looks like this:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:51080/";
string customerApi = "customer/1";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
//Response
HttpResponseMessage response = await client.GetAsync(customerApi);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
Hope anybody can help!
Upvotes: 2
Views: 11813
Reputation: 372
Try this:
client.DefaultRequestHeaders.Add("X-Version","1");
Upvotes: 3
Reputation: 56726
Collection behind DefaultRequestHeaders
has Add method which allows you to add whatever header you need:
client.DefaultRequestHeaders.Add("headerName", sesssionID);
Upvotes: 0