Cómo agregar y obtener valores de encabezado en WebAPI
Necesito crear un método POST en WebAPI para poder enviar datos desde la aplicación al método WebAPI. No puedo obtener el valor del encabezado.
Aquí he agregado valores de encabezado en la aplicación:
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);
}
Siguiendo el método post de WebAPI:
public string Postsam([FromBody]object jsonData)
{
HttpRequestMessage re = new HttpRequestMessage();
var headers = re.Headers;
if (headers.Contains("Custom"))
{
string token = headers.GetValues("Custom").First();
}
}
¿Cuál es el método correcto para obtener valores de encabezado?
Gracias.
7 answers
En el lado de la API web, simplemente use Request object en lugar de crear un nuevo HttpRequestMessage
var re = Request;
var headers = re.Headers;
if (headers.Contains("Custom"))
{
string token = headers.GetValues("Custom").First();
}
return null;
Salida -
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-28 11:59:49
Supongamos que tenemos un controlador API ProductsController: ApiController
Hay una función Get que devuelve algún valor y espera algún encabezado de entrada (por ejemplo. Nombre de usuario y contraseña)
[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);
}
Ahora podemos enviar la solicitud desde la página usando jQuery:
$.ajax({
url: 'api/products/10',
type: 'GET',
headers: { 'username': 'test','password':'123' },
success: function (data) {
alert(data);
},
failure: function (result) {
alert('Error: ' + result);
}
});
Espero que esto ayude a alguien ...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-21 09:10:15
Otra forma usando el método TryGetValues.
public string Postsam([FromBody]object jsonData)
{
IEnumerable<string> headerValues;
if (Request.Headers.TryGetValues("Custom", out headerValues))
{
string token = headerValues.First();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-05 01:03:22
Pruebe estas líneas de códigos que funcionan en mi caso:
IEnumerable<string> values = new List<string>();
this.Request.Headers.TryGetValues("Authorization", out values);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-01 08:37:12
En caso de que alguien esté usando ASP.NET Núcleo para encuadernación de modelos,
Https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding
Hay soporte incorporado para recuperar valores del encabezado utilizando el atributo [FromHeader]
public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
return $"Host: {Host} Content-Type: {Content-Type}";
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-16 20:04:31
Necesita obtener el HttpRequestMessage del actual OperationContext. Usando OperationContext puedes hacerlo así
OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
string customHeaderValue = requestProperty.Headers["Custom"];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-28 11:58:07
Para. NET Core:
string Token = Request.Headers["Custom"];
O
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);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-22 07:00:38