使用Nuget Core DLL设置包凭据

时间:2013-09-03 14:16:44

标签: c# nuget

我想在Http Autentication的私有Feed中获取包列表。这是我的代码,当我调用ListPlugins方法时出现401错误,如何设置凭据?

public  class PluginManager
{
    private readonly string _pluginFolder;
    private readonly IPackageRepository _packageRepository;
    private readonly PackageManager _packageManager;

    public PluginManager(string plugInFolder, string packageRepositoryAddres)
    {
        _pluginFolder = plugInFolder;
        _packageRepository = PackageRepositoryFactory.Default.CreateRepository(packageRepositoryAddres);
        _packageManager = new PackageManager(_packageRepository, _pluginFolder);  
    }

    public IEnumerable<PluginModel> ListPlugins()
    {
        IPackage dummy = null;

        var result =  _packageManager.SourceRepository.GetPackages()
            .OrderBy(p => p.Id)
            .ToList()
            .Select(p => new PluginModel()
            {
                PackageId = p.Id,
                PackageVersion = p.Version.ToString(),
                PackageDescription = p.Description,
                IsInstalled = _packageManager.LocalRepository.TryFindPackage(p.Id, p.Version, out dummy)
            })
            .ToList();

        return result;
    }

    public void Install(string packageId, string packageVersion)
    {
        _packageManager.InstallPackage(packageId, new SemanticVersion(packageVersion));
    }

    public void Uninstall(string packageId, string packageVersion)
    {
        _packageManager.UninstallPackage(packageId, new SemanticVersion(packageVersion));
    }
}

1 个答案:

答案 0 :(得分:5)

实现此目的的一种方法是在Visual Studio和SharpDevelop中运行NuGet,即实现自己的ICredentialProvider或使用NuGet.Core中提供的SettingsCredentialProvider类。设置凭据提供程序将读取NuGet.config文件中的任何凭据。

例如,在SharpDevelop和MonoDevelop中,以下代码使用设置提供程序和自定义提供程序:

    static void InitializeCredentialProvider()
    {
        ISettings settings = Settings.LoadDefaultSettings(null, null, null);
        var packageSourceProvider = new PackageSourceProvider(settings);
        var credentialProvider = new SettingsCredentialProvider(new SharpDevelopCredentialProvider(), packageSourceProvider);

        HttpClient.DefaultCredentialProvider = credentialProvider;
    }

自定义凭据提供程序,至少在SharpDevelop中当前没有任何操作,在Visual Studio中它会提示用户输入凭据。您可以忽略设置提供程序,只需使用自定义凭据提供程序。 SharpDevelop中凭据提供程序的当前实现是:

public class SharpDevelopCredentialProvider : ICredentialProvider
{
    public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
    {
        return null;
    }
}

因此,您可以从自定义凭据提供程序类中的GetCredentials方法返回凭据。

需要在HttpClient上设置提供程序。您正在使用PackageRepositoryFactory类,因此如果您的包源是一个url而不是一个文件,它将使用HttpClient。