gpt4 book ai didi

c# - 在C#中使用基本身份验证调用WEB API

转载 作者:行者123 更新时间:2023-12-03 15:21:37 25 4
gpt4 key购买 nike

我编写了一个有效的WEB API,并向该API添加了基本身份验证(用户名是“testing”,密码是“123456”)。但是,当尝试从我的Web表单调用该API时,我总是收到“(401)未经授权”消息。要成功调用API,我应该在网络代码中进行哪些更改?

 string url = String.Format("http://example.com"); //here I have the correct url for my API
HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);
requestObj.Method = "Get";
requestObj.PreAuthenticate = true;
requestObj.Credentials = new NetworkCredential("testing", "123456");
HttpWebResponse responseObj = null;
responseObj = (HttpWebResponse)requestObj.GetResponse();
string strresult = null;
using (Stream stream = responseObj.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresult = sr.ReadToEnd();
sr.Close();
}

这是我的API根据身份验证搜索的内容:
actionContext.Request.Headers.Authorization.Parameter

我应该添加标题而不是NetworkCredential还是同一件事?

最佳答案

这应该有助于:

    HttpMessageHandler handler = new HttpClientHandler()
{
};

var httpClient = new HttpClient(handler)
{
BaseAddress = new Uri(url),
Timeout = new TimeSpan(0, 2, 0)
};

httpClient.DefaultRequestHeaders.Add("ContentType", "application/json");

//This is the key section you were missing
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("testing:123456");
string val = System.Convert.ToBase64String(plainTextBytes);
httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + val);

HttpResponseMessage response = httpClient.GetAsync(url).Result;
string content = string.Empty;

using (StreamReader stream = new StreamReader(response.Content.ReadAsStreamAsync().Result, System.Text.Encoding.GetEncoding(_encoding)))
{
content = stream.ReadToEnd();
}

关于c# - 在C#中使用基本身份验证调用WEB API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57665326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com