Come aggiungere e ottenere i valori di intestazione in WebApi


99

Devo creare un metodo POST in WebApi in modo da poter inviare i dati dall'applicazione al metodo WebApi. Non riesco a ottenere il valore dell'intestazione.

Qui ho aggiunto i valori di intestazione nell'applicazione:

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

Seguendo il metodo di pubblicazione 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();
        }
    }

Qual è il metodo corretto per ottenere i valori di intestazione?

Grazie.

Risposte:


186

Sul lato API Web, usa semplicemente l'oggetto Request invece di creare un nuovo HttpRequestMessage

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

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

    return null;

Produzione -

inserisci qui la descrizione dell'immagine


Non puoi usare string token = headers.GetValues("Custom").FirstOrDefault();? Modifica: ho appena notato che stavi abbinando lo stile Qs originale.
Aidanapword

Rispondendo alla mia D: No. I headers.GetValues("somethingNotFound")lanci un InvalidOperationException.
Aidanapword

Uso beforeSendin JQuery ajax per inviare l'intestazione?
Si8

Perfetto ... ho usato il beforeSende ha funzionato. Fantastico :) +1
Si8

qual è il tipo di variabile Request e posso accedervi all'interno del metodo controller? Sto usando web api 2. Quale spazio dei nomi devo importare?
lohiarahul

21

Supponiamo di avere un controller API ProductsController: ApiController

C'è una funzione Get che restituisce un valore e si aspetta un'intestazione di input (ad es. UserName e 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);
}

Ora possiamo inviare la richiesta dalla pagina utilizzando JQuery:

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

Spero che questo aiuti qualcuno ...


9

Un altro modo utilizzando un metodo TryGetValues.

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

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

6

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


5

prova queste linee di codici che funzionano nel mio caso:

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

5

Come qualcuno ha già sottolineato come farlo con .Net Core, se la tua intestazione contiene un "-" o qualche altro carattere .Net non consente, puoi fare qualcosa come:

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

1

Per WEB API 2.0:

Ho dovuto usare Request.Content.Headersinvece di Request.Headers

e poi ho dichiarato un'estestione come sotto

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

E poi l'ho invocato in questo modo.

  var headerValue = Request.Content.Headers.GetHeader("custom-header-key", "default-value");

Spero possa essere utile


0

È necessario ottenere HttpRequestMessage dall'oggetto OperationContext corrente. Usando OperationContext puoi farlo in questo modo

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

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

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

0

Per .net Core nel metodo GET, puoi fare in questo modo:

 StringValues value1;
 string DeviceId = string.Empty;

  if (Request.Headers.TryGetValue("param1", out value1))
      {
                DeviceId = value1.FirstOrDefault();
      }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.