How to add and get Header values in WebApi

前端 未结 10 1574
既然无缘
既然无缘 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:25

    For .net Core in GET method, you can do like this:

     StringValues value1;
     string DeviceId = string.Empty;
    
      if (Request.Headers.TryGetValue("param1", out value1))
          {
                    DeviceId = value1.FirstOrDefault();
          }
    
    0 讨论(0)
  • 2020-12-02 06:28

    Another way using a the TryGetValues method.

    public string Postsam([FromBody]object jsonData)
    {
        IEnumerable<string> headerValues;
    
        if (Request.Headers.TryGetValues("Custom", out headerValues))
        {
            string token = headerValues.First();
        }
    }   
    
    0 讨论(0)
  • 2020-12-02 06:30

    Suppose we have a API Controller ProductsController : ApiController

    There is a Get function which returns some value and expects some input header (for eg. UserName & Password)

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

    Now we can send the request from page using JQuery:

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

    Hope this helps someone ...

    0 讨论(0)
  • 2020-12-02 06:36

    For .NET Core:

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

    Or

    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);
    }
    
    0 讨论(0)
  • 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

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

    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

    0 讨论(0)
  • 2020-12-02 06:40

    On the Web API side, simply use Request object instead of creating new HttpRequestMessage

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

    Output -

    enter image description here

    0 讨论(0)
提交回复
热议问题