gpt4 book ai didi

c# - 如何在 WebApi 中添加和获取 Header 值

转载 作者:IT王子 更新时间:2023-10-29 03:39:22 27 4
gpt4 key购买 nike

我需要在 WebApi 中创建一个 POST 方法,这样我就可以将数据从应用程序发送到 WebApi 方法。我无法获取 header 值。

这里我在应用程序中添加了 header 值:

 using (var client = new WebClient())
{
// Set the header so it knows we are sending JSON.
client.Headers[HttpRequestHeader.ContentType] = "application/json";

client.Headers.Add("Custom", "sample");
// Make the request
var response = client.UploadString(url, jsonObj);
}

按照WebApi post方法:

 public string Postsam([FromBody]object jsonData)
{
HttpRequestMessage re = new HttpRequestMessage();
var headers = re.Headers;

if (headers.Contains("Custom"))
{
string token = headers.GetValues("Custom").First();
}
}

获取 header 值的正确方法是什么?

谢谢。

最佳答案

在 Web API 端,只需使用 Request 对象而不是创建新的 HttpRequestMessage

     var re = Request;
var headers = re.Headers;

if (headers.Contains("Custom"))
{
string token = headers.GetValues("Custom").First();
}

return null;

输出-

enter image description here

关于c# - 如何在 WebApi 中添加和获取 Header 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21404734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com