Programing

WebApi에서 헤더 값을 추가하고 가져 오는 방법

lottogame 2020. 10. 7. 07:12
반응형

WebApi에서 헤더 값을 추가하고 가져 오는 방법


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 게시 방법 :

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

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

헤더 값을 가져 오는 올바른 방법은 무엇입니까?

감사.


웹 API 측에서는 새 HttpRequestMessage를 생성하는 대신 Request 객체를 사용하면됩니다.

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

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

    return null;

출력-

여기에 이미지 설명 입력


API 컨트롤러 ProductsController : ApiController가 있다고 가정합니다.

일부 값을 반환하고 일부 입력 헤더 (예 : UserName & Password)를 예상하는 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);
    }
});

이것이 누군가에게 도움이되기를 바랍니다 ...


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/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}";
}

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

누군가 이미 .Net Core로이 작업을 수행하는 방법을 지적했듯이 헤더에 "-"또는 .Net이 허용하지 않는 다른 문자가 포함 된 경우 다음과 같이 할 수 있습니다.

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

현재 OperationContext에서 HttpRequestMessage를 가져와야합니다. OperationContext를 사용하면 그렇게 할 수 있습니다.

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

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

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

GET 메서드의 .net Core의 경우 다음과 같이 할 수 있습니다.

 StringValues value1;
 string DeviceId = string.Empty;

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

참고 URL : https://stackoverflow.com/questions/21404734/how-to-add-and-get-header-values-in-webapi

반응형