【问题标题】:How to add and get Header values in WebApi如何在 WebApi 中添加和获取 Header 值
【发布时间】:2014-02-19 16:49:11
【问题描述】:

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

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

 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();
        }
    }

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

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 c#-4.0 asp.net-web-api


    【解决方案1】:

    您需要从当前的 OperationContext 中获取 HttpRequestMessage。使用 OperationContext 你可以这样做

    OperationContext context = OperationContext.Current;
    MessageProperties messageProperties = context.IncomingMessageProperties;
    
    HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
    
    string customHeaderValue = requestProperty.Headers["Custom"];
    

    【讨论】:

      【解决方案2】:

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

           var re = Request;
          var headers = re.Headers;
      
          if (headers.Contains("Custom"))
          {
              string token = headers.GetValues("Custom").First();
          }
      
          return null;
      

      输出 -

      【讨论】:

      • 不能用string token = headers.GetValues("Custom").FirstOrDefault();吗?编辑:刚刚注意到您匹配的是原始 Qs 样式。
      • 回答我自己的问题:不。headers.GetValues("somethingNotFound") 抛出 InvalidOperationException
      • 我是否在 JQuery ajax 中使用beforeSend 发送标头?
      • 完美...我使用了beforeSend,它成功了。太棒了:) +1
      • Request 变量的类型是什么,我可以在控制器方法中访问它吗?我正在使用 web api 2。我需要导入什么命名空间?
      【解决方案3】:

      另一种使用 TryGetValues 方法的方式。

      public string Postsam([FromBody]object jsonData)
      {
          IEnumerable<string> headerValues;
      
          if (Request.Headers.TryGetValues("Custom", out headerValues))
          {
              string token = headerValues.First();
          }
      }   
      

      【讨论】:

        【解决方案4】:

        假设我们有一个 API 控制器 ProductsController : ApiController

        有一个 Get 函数会返回一些值并需要一些输入标头(例如,用户名和密码)

        [HttpGet]
        public IHttpActionResult GetProduct(int id)
        {
            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            string token = string.Empty;
            string pwd = string.Empty;
            if (headers.Contains("username"))
            {
                token = headers.GetValues("username").First();
            }
            if (headers.Contains("password"))
            {
                pwd = headers.GetValues("password").First();
            }
            //code to authenticate and return some thing
            if (!Authenticated(token, pwd)
                return Unauthorized();
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
        

        现在我们可以使用 JQuery 从页面发送请求:

        $.ajax({
            url: 'api/products/10',
            type: 'GET',
            headers: { 'username': 'test','password':'123' },
            success: function (data) {
                alert(data);
            },
            failure: function (result) {
                alert('Error: ' + result);
            }
        });
        

        希望这对某人有所帮助...

        【讨论】:

          【解决方案5】:

          在我的情况下尝试这些代码行:

          IEnumerable<string> values = new List<string>();
          this.Request.Headers.TryGetValues("Authorization", out values);
          

          【讨论】:

            【解决方案6】:

            如果有人使用 ASP.NET Core 进行模型绑定,

            https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

            内置支持使用 [FromHeader] 属性从标头中检索值

            public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
            {
                 return $"Host: {Host} Content-Type: {Content-Type}";
            }
            

            【讨论】:

            • Content-Type 不是有效的 C# 标识符
            • 我以 x-publisher 的身份发送标头值,我应该如何处理。
            【解决方案7】:

            对于 .NET Core:

            string Token = Request.Headers["Custom"];
            

            或者

            var re = Request;
            var headers = re.Headers;
            string token = string.Empty;
            StringValues x = default(StringValues);
            if (headers.ContainsKey("Custom"))
            {
               var m = headers.TryGetValue("Custom", out x);
            }
            

            【讨论】:

              【解决方案8】:

              正如有人已经指出如何使用 .Net Core 执行此操作,如果您的标题包含“-”或其他 .Net 不允许的字符,您可以执行以下操作:

              public string Test([FromHeader]string host, [FromHeader(Name = "Content-Type")] string contentType)
              {
              }
              

              【讨论】:

              • 谢谢,这是我正在寻找的!
              【解决方案9】:

              对于 .net Core 的 GET 方法,你可以这样做:

               StringValues value1;
               string DeviceId = string.Empty;
              
                if (Request.Headers.TryGetValue("param1", out value1))
                    {
                              DeviceId = value1.FirstOrDefault();
                    }
              

              【讨论】:

                【解决方案10】:

                对于 WEB API 2.0:

                我必须使用Request.Content.Headers 而不是Request.Headers

                然后我如下声明了一个扩展

                  /// <summary>
                    /// Returns an individual HTTP Header value
                    /// </summary>
                    /// <param name="headers"></param>
                    /// <param name="key"></param>
                    /// <returns></returns>
                    public static string GetHeader(this HttpContentHeaders headers, string key, string defaultValue)
                    {
                        IEnumerable<string> keys = null;
                        if (!headers.TryGetValues(key, out keys))
                            return defaultValue;
                
                        return keys.First();
                    }
                

                然后我通过这种方式调用它。

                  var headerValue = Request.Content.Headers.GetHeader("custom-header-key", "default-value");
                

                希望对你有帮助

                【讨论】:

                  【解决方案11】:
                  app.MapGet("/", ([FromHeader(Name = "User-Agent")] string data) =>
                  {
                      return $"User agent header is: {data}";
                  });
                  

                  【讨论】:

                    【解决方案12】:

                    获取标头值的简单函数,具有使用 TryGetValue 的“单线”变体:

                    private string GetHeaderValue(string key) =>
                        Request.Headers.TryGetValue(key, out var value)
                            ? value.First()
                            : null;
                    
                    var headerValue = GetHeaderValue("Custom");
                    

                    【讨论】:

                      猜你喜欢
                      • 2012-11-24
                      • 1970-01-01
                      • 2014-11-04
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2014-02-15
                      • 1970-01-01
                      • 2021-06-25
                      相关资源
                      最近更新 更多