我正在尝试将自定义标头添加到我的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);
}
}
希望有人可以帮忙!
提前致谢!
试试这个:
client.DefaultRequestHeaders.Add("X-Version","1");
DefaultRequestHeaders
背后的集合有Add方法,允许你添加你需要的任何标题:
client.DefaultRequestHeaders.Add("headerName", sesssionID);