如何在WebApi中添加和获取Header值


99

我需要在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();
        }
    }

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

谢谢。

Answers:


186

在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样式。
Aidanapword

回答我自己的问题:不。headers.GetValues("somethingNotFound")抛出一个InvalidOperationException
Aidanapword

我可以beforeSend在JQuery ajax中使用以发送标头吗?
2013年

完美...我使用,beforeSend并且效果很好。好极了:) +1
Si8

Request变量的类型是什么,我可以在controller方法内访问它吗?我正在使用Web API2。我需要导入什么名称空间?
lohiarahul

21

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

有一个Get函数,该函数返回一些值并需要一些输入标头(例如,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);
}

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

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

希望这可以帮助某人...


9

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

public string Postsam([FromBody]object jsonData)
{
    IEnumerable<string> headerValues;

    if (Request.Headers.TryGetValues("Custom", out headerValues))
    {
        string token = headerValues.First();
    }
}   

6

对于.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);
}



5

正如某人已经指出了如何使用.Net Core进行操作一样,如果标头中包含“-”或其他字符。

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

1

对于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");

希望对您有所帮助


0

您需要从当前OperationContext获取HttpRequestMessage。使用OperationContext可以像这样

OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;

HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

string customHeaderValue = requestProperty.Headers["Custom"];

0

对于.NET Core中的GET方法,您可以执行以下操作:

 StringValues value1;
 string DeviceId = string.Empty;

  if (Request.Headers.TryGetValue("param1", out value1))
      {
                DeviceId = value1.FirstOrDefault();
      }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.