【问题标题】:How to add a custom header to HttpClient()?如何向 HttpClient() 添加自定义标头?
【发布时间】:2019-09-12 15:41:19
【问题描述】:

我正在尝试将自定义标头添加到我的 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);
        }
    }

希望任何人都可以提供帮助!

提前致谢!

【问题讨论】:

  • 那会是哪个标题名称?

标签: c# asp.net-mvc api header custom-headers


【解决方案1】:

试试这个:

client.DefaultRequestHeaders.Add("X-Version","1");

【讨论】:

  • 当我尝试这个并运行应用程序并使用检查器工具 -> 网络时,我查看了它没有出现的标题。
【解决方案2】:

DefaultRequestHeaders 后面的集合具有 Add 方法,可让您添加所需的任何标题:

client.DefaultRequestHeaders.Add("headerName", sesssionID);

【讨论】:

  • 当我尝试这个并运行应用程序并使用检查器工具 -> 网络时,我查看了它没有出现的标题。
猜你喜欢
  • 1970-01-01
  • 2013-02-14
  • 2013-05-15
  • 1970-01-01
  • 2019-02-19
  • 2012-11-15
  • 1970-01-01
  • 2019-09-13
  • 2021-12-23
相关资源
最近更新 更多