WebApiでヘッダー値を追加および取得する方法 質問する

WebApiでヘッダー値を追加および取得する方法 質問する

アプリケーションから WebApi メソッドにデータを送信できるように、WebApi で POST メソッドを作成する必要があります。ヘッダー値を取得できません。

ここで、アプリケーションにヘッダー値を追加しました:

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 post メソッドに従います。

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

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

ヘッダー値を取得するための正しい方法は何ですか?

ありがとう。

ベストアンサー1

Web API側では、新しいHttpRequestMessageを作成する代わりに、単にRequestオブジェクトを使用します。

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

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

return null;

出力 -

ここに画像の説明を入力してください

おすすめ記事