好吧,所以我正在编写一个程序来访问RESTful服务,但我首先必须为网站提供身份验证。我有有效的凭据,我的整个代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net;
using System.IO;
namespace AccessAPI
{
class Program
{
static void Main(string[] args)
{
string uri = "http://domainName/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
string auth = CreateAuthorization("http://domainName/", "my\\username", "password");
request.Headers["Authorization"] = "Basic " + auth;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
}
static string CreateAuthorization(string realm, string userName, string password)
{
string auth = ((realm != null) && (realm.Length > 0) ?
realm + @"\" : "") + userName + ":" + password;
auth = Convert.ToBase64String(Encoding.Default.GetBytes(auth));
return auth;
}
}
}
我使用其他论坛上发布的一些解决方案来实现这一目标。虽然这对某些人来说似乎有用,但它并不适合我。首先,我知道凭据是准确的。我可以通过Web浏览器输入它们,它们的行为就像它们应该的那样。此外,我确保其中的任何“\”(用户名中有一个)在代码中用“\\”表示。但是,每次我运行时,我都会继续“远程服务器返回错误:(401)未经授权。” 有人可以帮我解决这个问题吗?谢谢你的时间!
答案 0 :(得分:0)
从上面的代码中,当“auth”字符串被组合时,auth字符串将如下所示:“http://domainName/:my \ username:password”
auth字符串应该具有以下格式:domainName \ username:password(域名是可选的)。