如何在 WebApi 中添加和获取 Header 值 [英] How to add and get Header values in WebApi

查看:115
本文介绍了如何在 WebApi 中添加和获取 Header 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 the application:

 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方法:

Following the WebApi post method:

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

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

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

What is the correct method for getting header values?

谢谢.

推荐答案

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

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;

输出 -

这篇关于如何在 WebApi 中添加和获取 Header 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆