我有一个ASP.NET MVC 4项目,当我使用Web请求进行HTTP调用时,标题将无法通过。
这是我的代码:
HttpWebRequest client = (HttpWebRequest)WebRequest.Create(url);
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("user1" + ":" + "test"));
client.Headers.Add("Authorization", "Basic " + svcCredentials);
//Just some example code to parse the JSON response using the JavaScriptSerializer
using (WebResponse svcResponse = (HttpWebResponse)client.GetResponse())
{
using (StreamReader sr = new StreamReader(svcResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonTxt = sr.ReadToEnd();
}
}
答案 0 :(得分:0)
试试这个:
string encCred = Convert.ToBase64String(Encoding.ASCII.GetBytes("user1" + ":" + "test"));
string credential = string.Format("{0} {1}", "Basic", encCred);
client.Headers[HttpRequestHeader.Authorization] = credential;
而不是:
client.Headers.Add("Authorization", "Basic " + svcCredentials);
希望它有所帮助。