[英]C# Call RestAPI with basic Authentication
我是 RestAPI 的新手,不確定如何調用它並向其傳遞憑據。 我有一個帶有“POST”按鈕的 Windows Forms。 本項目使用.Net framework 4.5構建。 當用戶單擊此按鈕時,它會使用下面的 class 執行代碼。 在此調用中,有一個調用 RestAPI 的 Post 方法。 此 RestApi 需要基本身份驗證。 任何幫助都會很棒。
public static class CallRestAPI
{
private static readonly string baseURL = "https://servername/fscmRestApi/resources/11.13.18.05/erpintegrations";
public static async Task<string> Post(string name, string job)
{
var inputData = new Dictionary<string, string>
{
{"name", name },
{"job", job }
};
var input = new FormUrlEncodedContent(inputData);
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage res = await client.PostAsync(baseURL + "users", input))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
return data;
}
}
}
}
return string.Empty;
}
}
您必須添加授權 header:
var byteArray = Encoding.ASCII.GetBytes($"{UserName}:{Password}");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.