[英]How to add a custom header to HttpClient()?
我正在嘗試將自定義標頭添加到我的Web應用程序的請求標頭中。 在我的Web應用程序中,我從web api中檢索數據,在此請求中,我想添加一個包含字符串sessionID的自定義標頭。 我正在尋找一個通用的解決方案,這樣我就不必在每次調用之前添加相同的代碼。
我的控制器看起來像這樣:
[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);
}
}
希望有人可以幫忙!
提前致謝!
DefaultRequestHeaders
背后的集合具有Add方法,允許您添加所需的任何標頭:
client.DefaultRequestHeaders.Add("headerName", sesssionID);
嘗試這個:
client.DefaultRequestHeaders.Add("X-Version","1");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.