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);
        }
遵循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();
        }
    }
获取标头值的正确方法是什么?
谢谢.
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;
输出 -

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);
}
现在我们可以使用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
正如有人已经指出如何使用 .Net Core 执行此操作,如果您的标头包含“-”或其他一些 .Net 不允许的字符,您可以执行以下操作:
public string Test([FromHeader]string host, [FromHeader(Name = "Content-Type")] string contentType)
{
}
对于 .NET 核心:
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);
}
使用TryGetValues方法的另一种方法.
public string Postsam([FromBody]object jsonData)
{
    IEnumerable<string> headerValues;
    if (Request.Headers.TryGetValues("Custom", out headerValues))
    {
        string token = headerValues.First();
    }
}   
尝试在我的情况下工作的这些代码行:
IEnumerable<string> values = new List<string>();
this.Request.Headers.TryGetValues("Authorization", out values);
如果有人使用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}";
}
| 归档时间: | 
 | 
| 查看次数: | 202260 次 | 
| 最近记录: |