Jak dodawać i pobierać wartości nagłówków w WebApi

Muszę utworzyć metodę POST w WebApi, aby móc wysyłać dane z aplikacji do metody WebApi. Nie jestem w stanie uzyskać wartości nagłówka.

Tutaj dodałem wartości nagłówka w aplikacji:

 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);
        }

Stosując metodę Post 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();
        }
    }

Jaka jest prawidłowa metoda pobierania wartości nagłówka?

Dzięki.
Author: AndrewRalon, 2014-01-28

7 answers

Po Stronie Web API, po prostu użyj obiektu Request zamiast tworzyć nowy HttpRequestMessage

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

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

    return null;

Wyjście -

Tutaj wpisz opis obrazka

 138
Author: ramiramilu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-28 11:59:49

Załóżmy, że mamy Kontroler API ProductsController: ApiController

Istnieje funkcja Get, która zwraca jakąś wartość i oczekuje jakiegoś nagłówka wejściowego (np. Nazwa Użytkownika I Hasło)

[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);
}

Teraz możemy wysłać żądanie ze strony używając JQuery:

$.ajax({
    url: 'api/products/10',
    type: 'GET',
    headers: { 'username': 'test','password':'123' },
    success: function (data) {
        alert(data);
    },
    failure: function (result) {
        alert('Error: ' + result);
    }
});
Mam nadzieję, że to komuś pomoże ...
 12
Author: Venugopal M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-21 09:10:15

Inny sposób przy użyciu metody TryGetValues.

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

    if (Request.Headers.TryGetValues("Custom", out headerValues))
    {
        string token = headerValues.First();
    }
}   
 6
Author: Schandlich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-05 01:03:22

Wypróbuj te kody działające w moim przypadku:

IEnumerable<string> values = new List<string>();
this.Request.Headers.TryGetValues("Authorization", out values);
 3
Author: Sufyan Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-01 08:37:12

W przypadku, gdy ktoś używa ASP.NET Core for model binding,

Https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

Istnieje wbudowana obsługa pobierania wartości z nagłówka za pomocą atrybutu [FromHeader]

public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
     return $"Host: {Host} Content-Type: {Content-Type}";
}
 2
Author: wonster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-16 20:04:31

Musisz pobrać HttpRequestMessage z bieżącej Operacjikontekst. Używając OperationContext możesz to zrobić tak

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

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

string customHeaderValue = requestProperty.Headers["Custom"];
 0
Author: Jehof,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-28 11:58:07

Dla. NET Core:

string Token = Request.Headers["Custom"];

Lub

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);
}
 0
Author: SaadK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 07:00:38