如何在WebApi中添加和获取标头值

83 c# asp.net-mvc c#-4.0 asp.net-mvc-4 asp.net-web-api

我需要在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);
        }
Run Code Online (Sandbox Code Playgroud)

遵循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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

ram*_*ilu 163

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

     var re = Request;
    var headers = re.Headers;

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

    return null;
Run Code Online (Sandbox Code Playgroud)

输出 -

在此输入图像描述


Ven*_*l M 18

假设我们有一个API Controller 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

希望这有助于某人......


小智 9

正如有人已经指出如何使用 .Net Core 执行此操作,如果您的标头包含“-”或其他一些 .Net 不允许的字符,您可以执行以下操作:

public string Test([FromHeader]string host, [FromHeader(Name = "Content-Type")] string contentType)
{
}
Run Code Online (Sandbox Code Playgroud)


Saa*_*adK 8

对于 .NET 核心:

string Token = Request.Headers["Custom"];
Run Code Online (Sandbox Code Playgroud)

或者

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);
}
Run Code Online (Sandbox Code Playgroud)


Sch*_*ich 7

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

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

    if (Request.Headers.TryGetValues("Custom", out headerValues))
    {
        string token = headerValues.First();
    }
}   
Run Code Online (Sandbox Code Playgroud)


Suf*_*mad 5

尝试在我的情况下工作的这些代码行:

IEnumerable<string> values = new List<string>();
this.Request.Headers.TryGetValues("Authorization", out values);
Run Code Online (Sandbox Code Playgroud)


won*_*ter 5

如果有人使用ASP.NET Core进行模型绑定,

https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/model-binding

内置支持使用[FromHeader]属性从标头中检索值

public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
     return $"Host: {Host} Content-Type: {Content-Type}";
}
Run Code Online (Sandbox Code Playgroud)

  • `Content-Type` 不是有效的 C# 标识符 (5认同)