无法使用System.Net API对REST端点的当前用户进行身份验证。以下示例返回401未经授权的
using (HttpClient client = new HttpClient())
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://rest/api/endpoint")
{
using (httpResponseMessage response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode)
//do something
}
}
}
如果我使用NSUrlConnection,我可以验证没问题。因此,NSUrlConnection必须如何传递凭证。以下是该代码的片段:
var request = new NSMutableUrlRequest(new NSUrl("http://rest/api/endpoint"), NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 0);
request["Accept"] = "application/json";
NSUrlConnection.SendAsynchronousRequest(request, NSOperationQueue.MainQueue, delegate(NSUrlResponse, response, NSData data, NSError error)
{
// successfully authenticated and do something with response
});
我想将我的服务代码包装在PCL中以与其他平台共享。因此,我想在System.Net api中完成所有工作。这可能吗?
更新:
我已经尝试使用HttpClientHandler并使用默认凭据以及CredentialCache.DefaultNetworkCredentials。让这个工作的唯一方法是硬编码我不想要的凭据。 System.Net堆栈似乎没有显示来自操作系统的凭据。
答案 0 :(得分:0)
我假设它使用默认身份验证。你可以使用带有HttpClientHandler的HttpClient来做到这一点,例如:
using (var handler = new HttpClientHandler {
UseDefaultCredentials = true
})
using (var client = new HttpClient(handler))
{
var result = await client.SendAsync(...);
}