C# 使用HttpWebRequest进行基本身份验证

C# 使用HttpWebRequest进行基本身份验证,c#,rest,uwp,webclient,C#,Rest,Uwp,Webclient,我正在制作一个类似邮递员的应用程序,并试图使用HttpWebRequest实现基本身份验证,但我总是以403禁止错误结束,我想这意味着我做错了什么 我目前正在使用WebHeaderCollection存储我的标题。 我构建的授权标头如下所示: 代码: 私有WebHeaderCollection添加授权(WebHeaderCollection wc) { if(expanderBasique.IsExpanded&!String.IsNullOrEmpty(BasiqueUserName.Text

我正在制作一个类似邮递员的应用程序,并试图使用
HttpWebRequest
实现基本身份验证,但我总是以
403禁止错误
结束,我想这意味着我做错了什么

我目前正在使用
WebHeaderCollection
存储我的标题。 我构建的授权标头如下所示:

代码:

私有WebHeaderCollection添加授权(WebHeaderCollection wc)
{
if(expanderBasique.IsExpanded&!String.IsNullOrEmpty(BasiqueUserName.Text)&&!String.IsNullOrEmpty(BasiquePassword.Password))
{
字符串username=BasiqueUserName.Text.Trim();
字符串password=BasiquePassword.password.Trim();
String encoded=System.Convert.ToBase64String(System.Text.Encoding.GetEncoding(“ISO-8859-1”).GetBytes(用户名+”:“+密码));
wc.添加(“授权”、“基本”+编码);
}
返回wc;
}
然后我将我的收藏链接到HttpWebRequest:

代码:

private async Task ExecuteHttpWebRequest()
{
var selectedMethode=Methode.SelectedItem作为文本块;
字符串方法=selectedMethode.Text;
HttpWebRequest webRequest=(HttpWebRequest)webRequest.Create(Query.Text);
WebHeaderCollection myWebHeaderCollection=webRequest.Headers;
myWebHeaderCollection=BuildHeaderCollection(myWebHeaderCollection);
myWebHeaderCollection=添加授权(myWebHeaderCollection);
webRequest.PreAuthenticate=true;
webRequest.Method=Method;
if(webRequest.Method==“POST”| | webRequest.Method==“PUT”| | webRequest.Method==“PATCH”)
{
byte[]data=Encoding.ASCII.GetBytes(Body.Text);
webRequest.ContentLength=data.Length;
使用(var stream=webRequest.GetRequestStream())
{
stream.Write(数据,0,数据长度);
}
}
return wait webRequest.GetResponseAsync();
}
我使用GitHub api使用自己的凭据尝试以下代码:

使用其他应用程序,如postman或restER,我得到了想要的结果,但我自己的结果总是出现403错误

我真的想坚持使用HttpWebRequest。
我尝试了堆栈溢出的各种解决方案,但没有成功: 或编辑:
根据FaizanRabbani的评论,我通过将UserAgent属性设置为httpwebrequest解决了问题:

代码:

private async Task ExecuteHttpWebRequest()
{
var selectedMethode=Methode.SelectedItem作为文本块;
字符串方法=selectedMethode.Text;
HttpWebRequest webRequest=(HttpWebRequest)webRequest.Create(Query.Text);
WebHeaderCollection myWebHeaderCollection=webRequest.Headers;
myWebHeaderCollection=BuildHeaderCollection(myWebHeaderCollection);
myWebHeaderCollection=添加授权(myWebHeaderCollection);
webRequest.PreAuthenticate=true;
webRequest.Method=Method;
webRequest.UserAgent=“某物”;
if(webRequest.Method==“POST”| | webRequest.Method==“PUT”| | webRequest.Method==“PATCH”)
{
byte[]data=Encoding.ASCII.GetBytes(Body.Text);
webRequest.ContentLength=data.Length;
使用(var stream=webRequest.GetRequestStream())
{
stream.Write(数据,0,数据长度);
}
}
return wait webRequest.GetResponseAsync();
}

您是否尝试设置用户代理
webRequest.UserAgent
?@FaizanRabbani我刚试过,效果不错!非常感谢。