无法在项目的标头中发送身份验证
本文关键字:身份验证 项目 | 更新日期: 2023-09-27 18:24:36
所以基本上我正在从外部托管源将web API集成到我的项目中。。但是xml存储在基本身份验证之后。因此,有人建议我在联系XML的位置时,需要将一些身份验证解析到HTTP请求的标头中。
以下是我目前正在使用的内容:
我已经创建了一个控制器,我的代码如下:
namespace com.tortoise.Controllers
{
public class VebraController : ApiController
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
string username = "user";
string password = "password";
string usernamePassword = ("username + : + password");
CredentialCache cache = new CredentialCache();
new cache.add Uri(url), "Basic", new class NetworkCredential(username, password));
request.Credentials = cache;
request.Headers.Add("Authorization", "Basic " // <- space here.
+ Convert.ToBase64String()(new Int64 ASCIIEncoding().GetBytes (usernamePassword));
// Get the token from the response:
string token = response.GetResponseHeader("Token");
}
任何帮助都很好。我在CredentialCache、ASCIIEncoding、ToBase64String()、GetBytes()和GetResponseHeader()中收到错误。
好吧,我已经修复了您的代码。现在应该编译它,假设您已经实际声明了正在使用的变量。我不能为你那样做请阅读评论你似乎需要大量的C#语法和语言练习,一般来说,你有很多无效的C#。希望这能有所帮助。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
string username = "user";
string password = "password";
//here I am declaring the NetworkCredentials. You do not need to put 'new class'
NetworkCredential myCredentials = new System.Net.NetworkCredential(username,password);
string usernamePassword = (username + password); //I assume you meant to concatenate them
CredentialCache cache = new CredentialCache();
cache.Add((Uri)url, "Basic", myCredentials); //you must declare url, not sure what you want it to be
request.Credentials = cache;
request.Headers.Add("Authorization", "Basic " // <- space here.
+ Convert.ToBase64String(Encoding.ASCII.GetBytes(usernamePassword)); //fixed this
// Get the token from the response:
string token = response.GetResponseHeader("Token"); //you need to declare response somewhere