Search code examples
c#odatacredentials

OData client obsolete credentials property in version 8.x


I read the change log for Microsoft.OData.Client 8.x. There is a statement "Obsolete Credentials property dropped from DataServiceContext class. The recommended way to configure credentials is through HttpClientHandler that can be provided using IHttpClientFactory." https://learn.microsoft.com/en-us/odata/changelog/odatalib-8x

I used to initialize Microsoft.OData.Client.DataServiceContext container this way:

Container _dataContext = new Container(new Uri(url))
{
    Credentials = CredentialCache.DefaultNetworkCredentials
};

I use Unchase Connected Service to consume OData. The initialization with credentials is no longer supported. Do you have any experience setting the credentials in a new recommended way?


Solution

  • After discussion with our team, we have found the solution by implementing a custom HTTP client factory. HttpClientHandler allows you to set the Credentials.

    public class DataContextFactory
    {
        public static Container CreateContainer(string uri)
        {
            var container = new Container(new Uri(uri))
            {
                HttpClientFactory = new CustomHttpClientFactory()
            };
            return container;
        }
    }
    

    The code of the custom factory is below...

    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);
        }
    }
    

    Finally, the usage...

    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;
        }
    }