How to add and get Header values in WebApi

前端 未结 10 1607
既然无缘
既然无缘 2020-12-02 05:45

I need to create a POST method in WebApi so I can send data from application to WebApi method. I\'m not able to get header value.

Here I have added header values in

10条回答
  •  被撕碎了的回忆
    2020-12-02 06:39

    For WEB API 2.0:

    I had to use Request.Content.Headers instead of Request.Headers

    and then i declared an extestion as below

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

    And then i invoked it by this way.

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

    I hope it might be helpful

提交回复
热议问题