我阅读了 Microsoft.OData.Client 8.x 的更改日志。有一个声明“从 DataServiceContext 类中删除了过时的凭据属性。配置凭据的推荐方法是通过可以使用 IHttpClientFactory 提供的 HttpClientHandler”。 https://learn.microsoft.com/en-us/odata/changelog/odatalib-8x
我曾经这样初始化 Microsoft.OData.Client.DataServiceContext 容器:
Container _dataContext = new Container(new Uri(url))
{
Credentials = CredentialCache.DefaultNetworkCredentials
};
我使用 Unchase Connected Service 来消费 OData。不再支持使用凭据进行初始化。您有以新的推荐方式设置凭据的经验吗?
经过我们团队的讨论,我们通过实现自定义 HTTP 客户端工厂找到了解决方案。
HttpClientHandler
允许您设置 Credentials
。
public class DataContextFactory
{
public static Container CreateContainer(string uri)
{
var container = new Container(new Uri(uri))
{
HttpClientFactory = new CustomHttpClientFactory()
};
return container;
}
}
定制工厂的代码如下...
public class CustomHttpClientFactory : IHttpClientFactory
{
public HttpClient CreateClient(string name)
{
return CreateHttpClient();
}
public static HttpClient CreateHttpClient()
{
var handler = new HttpClientHandler
{
Credentials = CredentialCache.DefaultNetworkCredentials
};
return new HttpClient(handler);
}
}
最后,用法...
public class ODataProvider
{
private static readonly string uri = "http://...../odata";
private static readonly Container _container = DataContextFactory.CreateContainer(uri);
public static List<Gen01Record> GetSifRecords(string runNumber)
{
if (!runNumber.IsNumeric()) return [];
var run = int.Parse(runNumber);
var records = _container.Communicator.GetSifInformationByRunNumber(run).GetAllPages().Select(x => x.Records).Single().ToList();
return records;
}
}