How to add and get Header values in WebApi

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

    try these line of codes working in my case:

    IEnumerable<string> values = new List<string>();
    this.Request.Headers.TryGetValues("Authorization", out values);
    
    0 讨论(0)
  • 2020-12-02 06:49

    In case someone is using ASP.NET Core for model binding,

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

    There's is built in support for retrieving values from the header using the [FromHeader] attribute

    public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
    {
         return $"Host: {Host} Content-Type: {Content-Type}";
    }
    
    0 讨论(0)
  • 2020-12-02 06:50

    As someone already pointed out how to do this with .Net Core, if your header contains a "-" or some other character .Net disallows, you can do something like:

    public string Test([FromHeader]string host, [FromHeader(Name = "Content-Type")] string contentType)
    {
    }
    
    0 讨论(0)
  • 2020-12-02 06:50

    You need to get the HttpRequestMessage from the current OperationContext. Using OperationContext you can do it like so

    OperationContext context = OperationContext.Current;
    MessageProperties messageProperties = context.IncomingMessageProperties;
    
    HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
    
    string customHeaderValue = requestProperty.Headers["Custom"];
    
    0 讨论(0)
提交回复
热议问题