簡體   English   中英

從 winForm 客戶端向 Web API 發送標頭

[英]sending headrs to web API from winForm client

我有一個簡單的演示 winform 應用程序,我試圖向 web api 發出帶有標頭的發布請求。 我從服務器收到訪問令牌和刷新令牌,並將其存儲在文本文件中。 我試圖通過發送帶有正文的刷新令牌並發送帶有標題的訪問令牌來發出發布請求,但我不知道如何在發布請求中包含標題。

這是我的帖子方法

public static async Task<string> sendMessage(string name, string contents)
        {
            

            using (HttpClient client = new HttpClient())
            {
                //reading the access token and refreash token from file
                StreamReader sr = new StreamReader(@"C:\Users\noorm\Desktop\noor.txt");
                string accessToken, refreashToken;
                accessToken = sr.ReadLine();
                refreashToken = sr.ReadLine();

                //defining new instance of message opject
                var newMessage = new messages()
                {
                    name = name,
                    content = contents,
                    refreashToken = refreashToken

                };
               
                //sening the opject using post async and returning the response
                var newPostJson = JsonConvert.SerializeObject(newMessage);
                var payLoad = new StringContent(newPostJson, Encoding.UTF8, "application/json");
                
                    using (HttpResponseMessage res = await client.PostAsync(baseURL + "/messages", payLoad))
                    {
                        using (HttpContent content = res.Content)
                        {

                            string data = await content.ReadAsStringAsync();
                            if (data != null)
                            {
                                return data;
                            }
                        }
                    }
                
            }


            return string.Empty;
        }

這是按鈕

private async void btnSend_Click(object sender, EventArgs e)
        {
            var responce = await restHelper.sendMessage(txtName.Text.Trim(),txtContent.Text.Trim());
            rtxt.Text = responce;
        }

您可以嘗試以下方法:

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");

這就是我能夠發送帶有標頭的訪問令牌的方式

client.DefaultRequestHeaders.Add("x-auth-token", accessToken);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM