Подтвердить что ты не робот

Как добавить и получить значения заголовка в WebApi

Мне нужно создать метод POST в WebApi, чтобы я мог отправлять данные из приложения в метод 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:

 public string Postsam([FromBody]object jsonData)
    {
        HttpRequestMessage re = new HttpRequestMessage();
        var headers = re.Headers;

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

Каков правильный метод получения значений заголовков?

Спасибо.

4b9b3361

Ответ 1

В стороне веб-API просто используйте объект Request вместо создания нового HttpRequestMessage

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

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

    return null;

Выход -

enter image description here

Ответ 2

Предположим, что у нас есть API-контроллер ПродуктыКонтроллер: ApiController

Существует функция Get, которая возвращает некоторое значение и ожидает некоторый заголовок ввода (например, имя пользователя и пароль)

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

Надеюсь, это поможет кому-то...

Ответ 3

Другой способ использования метода TryGetValues.

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

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

Ответ 4

попробуйте эти строки кодов, работающих в моем случае:

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

Ответ 5

Если кто-то использует ASP.NET Core для привязки модели,

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

Встроена поддержка извлечения значений из заголовка с использованием атрибута [FromHeader]

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

Ответ 6

Для .NET Core:

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

Ответ 7

Как уже указывалось, как это сделать с помощью .Net Core, если ваш заголовок содержит символ "-" или другой символ, запрещающий .Net, вы можете сделать что-то вроде:

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

Ответ 8

Вам нужно получить HttpRequestMessage из текущего OperationContext. Используя OperationContext, вы можете сделать это так

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

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

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

Ответ 9

Для .net Core в методе GET вы можете сделать так:

 StringValues value1;
 string DeviceId = string.Empty;

  if (Request.Headers.TryGetValue("param1", out value1))
      {
                DeviceId = value1.FirstOrDefault();
      }