我正在尝试发布到使用基本身份验证的Web API。当我使用Fiddler POST时,我能够成功发布数据。现在我正在尝试在C#控制台应用程序中执行相同操作但我继续获得401 Unauthorized响应。
当我通过Debug运行代码时,我可以播种凭据正在进行Base64编码。在网上做一些研究我相信我有正确的代码。有人看我是否遗漏了什么?
if (lstEmployee != null && lstEmployee.Count > 0)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://website.com/api/employees/upload";);
//set credentials and add them to the client header
string credentials = Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
//set to use JSON
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
foreach (var employee in lstEmployee)
{
//Convert to JSON with Newtonsoft
string employeeJSON = JsonConvert.SerializeObject(employee);
HttpResponseMessage response = client.PostAsJsonAsync(fullServiceURL, employeeJSON).Result;
if (response.IsSuccessStatusCode)
{
//If successfull, do something.
}
else
{
logger.Error("Error posting to Web API. Employee: {0} | {1} ({2})", employee.EmployeeNumber, (int)response.StatusCode, response.ReasonPhrase);
}
}
}
}
catch (Exception ex)
{
logger.Error("Error posting to Web API. | {0} | Trace: {1}", ex.Message, ex.StackTrace);
}
}
else
{
logger.Info("No records found.");
}
在Fiddler中,我刚刚将以下内容添加到作曲家选项卡中的Header以及正文中的一些JSON数据,并且它有效。
Authorization: Basic abChaXJ3YXlzLmludGVncmF0aW9uOnRlc3Q0ZGNhYTIwMTU=
Host: services.website.com
Content-Length: 374
Content-Type: application/json; charset=utf-8
**更新**
我将代码调整为以下内容。现在我收到错误状态400“错误请求”。看起来它抱怨数据格式错误。但是,我记录了JSON列表值并将其添加到Fiddler的主体中。我可以在Fiddler中发布捕获的JSON就好了。我不知道还有什么要检查,看看它有什么不妥。
以下是通过Newtonsoft后我的JSON列表的结果。我只是为了测试目的而拉一条记录
[{"EmployeeNumber":"22449","CompanyHireDate":"2014-12-15T00:00:00","Username":"EN022449","LastName":"AVIVA","FirstName":"JOE","MiddleInitial":null,"BirthDate":"1967-10-06T00:00:00","PhoneNumber":null,"EmailAddress":"EN999-Joe.Aviva@company.com","Location":"BOS","Address1":null,"Address2":null,"City":null,"State":null,"Zip":null,"OverrideSeniorityOrder":0}]
这是我更新的代码:
if (lstEmployee != null && lstEmployee.Count > 0)
{
logger.Info("Employee count: " + lstEmployee.Count);
string baseUrl = "https://services.website.com/api/";
string serviceUrl = "employees/upload";
string fullServiceURL = baseUrl + serviceUrl;
logger.Debug("Web API Uri: " + fullServiceURL);
try
{
//Convert the list to JSON
string employeeJSON = JsonConvert.SerializeObject(lstEmployee);
logger.Debug("employeeJSON: " + employeeJSON);
//Add credentials to Client Handler
var credentials = new NetworkCredential("username", "password");
var handler = new HttpClientHandler { Credentials = credentials };
using (var client = new HttpClient(handler))
{
//set URI and to use JSON
client.BaseAddress = new Uri(fullServiceURL);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync(fullServiceURL, employeeJSON).Result;
if (response.IsSuccessStatusCode)
{
//success
}
else
{
logger.Error("Error posting to Web API. {0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
logger.Error("Error posting to Web API. | {0} | Trace: {1}", ex.Message, ex.StackTrace);
}
}
else
{
logger.Info("No records found.");
}
答案 0 :(得分:1)
.Net 4.5中引入的HttpClientHandler使您无需手动编码身份验证标头。像这样使用它:
var credentials = new NetworkCredential(userName, password);
var handler = new HttpClientHandler { Credentials = credentials };
using (var http = new HttpClient(handler))
{
// ...
}