这是我的Pull包装器,适用于我的本地网络:
internal MergeStatus Pull()
{
using (var repo = new Repository(repositoryRoot))
{
var merger = new Signature(userName,emailAddress,DateTimeOffset.UtcNow);
var options =new PullOptions {
FetchOptions = new FetchOptions()
{
CredentialsProvider = CredentialsHandler
}
};
MergeResult result = repo.Network.Pull(merger, options);
return result.Status;
}
}
以下显示我正在使用的CredentialsHandler以及使用UsernamePasswordCredentials的注释尝试,它给出了完全相同的结果。
public LibGit2Sharp.Handlers.CredentialsHandler CredentialsHandler
{
get
{
if (credentialsHandler_ == null)
{
credentialsHandler_ = (_url, _user, _cred) => new DefaultCredentials();
//This does not fix the 401 error on Jupiter box
//credentialsHandler_ = (_url, _user, _cred) => new UsernamePasswordCredentials
//{
// Username = userName,
// Password = pwd,
//};
}
return credentialsHandler_;
}
set
{
credentialsHandler_ = value;
}
}
Pull功能在本地网络上运行得很漂亮但是当我在不同网络上的机器上使用它但具有相同的目录结构并克隆git存储库时,我得到401错误:
LibGit2Sharp.LibGit2SharpException:请求失败,状态代码为: 在LibGit2Sharp.Core.Ensure.HandleError(Int32结果)处的401处 LibGit2Sharp.Core.Ensure.ZeroResult(Int32结果)at LibGit2Sharp.Core.Proxy.git_remote_fetch(RemoteSafeHandle远程, 签名签名,String logMessage) LibGit2Sharp.Network.DoFetch(RemoteSafeHandle remoteHandle, FetchOptions选项,签名签名,String logMessage) LibGit2Sharp.Network.Fetch(远程远程,FetchOptions选项, 签名签名,String logMessage) LibGit2Sharp.Network.Pull(签名合并,PullOptions选项)at GitFace.GitFileListController.Pull()in c:\ Code \ Workspace \ GitFace \ GitFileListController.cs:第190行
请注意,当我使用git bash并输入' git pull'时,我需要在本地和网络计算机上输入密码,但都成功从远程存储库中提取更改(FWIW,实际存储库位于本地网络上的TFS中)。我通过git bash进行拉取和推送的过程对于两台计算机是相同的,所以当libgit2sharp代码的行为不同时,我感到很惊讶。
注意:这不起作用:
private int GitCredentialHandler(out IntPtr ptr, IntPtr cUrl, IntPtr usernameFromUrl, GitCredentialType credTypes, IntPtr payload)
{
string url = LaxUtf8Marshaler.FromNative(cUrl);
string domain = ConfigurationManager.AppSettings["Domain"];
if (url.StartsWith(@"http://"))
{
url = string.Format(@"http://{0}\\\{1}", domain, url.Substring(7));
}
else if (url.StartsWith(@"https://"))
{
url = string.Format(@"https://{0}\\\{1}", domain, url.Substring(8));
}
string username = string.Format(@"{0}\{1}", domain, LaxUtf8Marshaler.FromNative(usernameFromUrl));
SupportedCredentialTypes types = default(SupportedCredentialTypes);
if (credTypes.HasFlag(GitCredentialType.UserPassPlaintext))
{
types |= SupportedCredentialTypes.UsernamePassword;
}
if (credTypes.HasFlag(GitCredentialType.Default))
{
types |= SupportedCredentialTypes.Default;
}
var cred = CredentialsProvider(url, username, types);
return cred.GitCredentialHandler(out ptr);
}