Download NuGet from behind a proxy using inline MSBuild Task

363 Views Asked by At

I am using the NuGet.targets file from NuGet to automatically download NuGet.exe and then restore the packets in my project.

This was working well, however at work we have a proxy and this method was failing due to a (407) Proxy Authentication Required Exception. I modified the targets file to use the proxy details and although this method works in an application it does not work in the MSBuild Task, the code is identical.

If I hardcode the proxy and my login details it works, when I build my solution NuGet.exe is downloaded and the packages are restored correctly. The problem only appears to be the authentication in the MSBuild task, I have absolutely no idea why. I have attached my modified code.

If anyone can help I'd appreciate it. Thanks

 <UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
    <ParameterGroup>
        <OutputFilename ParameterType="System.String" Required="true" />
    </ParameterGroup>
    <Task>
        <Reference Include="System.Core" />
        <Using Namespace="System" />
        <Using Namespace="System.IO" />
        <Using Namespace="System.Net" />
        <Using Namespace="Microsoft.Build.Framework" />
        <Using Namespace="Microsoft.Build.Utilities" />
        <Code Type="Fragment" Language="cs">
            <![CDATA[
            try 
            {
                OutputFilename = Path.GetFullPath(OutputFilename);

                Log.LogMessage("Downloading latest version of NuGet.exe...");

                using(WebClient webClient = new WebClient())
                {
                  webClient.UseDefaultCredentials = true;
                  webClient.Proxy = WebRequest.GetSystemWebProxy();
                  webClient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                  webClient.DownloadFile("https://www.nuget.org/nuget.exe", OutputFilename);

                  return true;
                }
            }
            catch (Exception ex) 
            {
                Log.LogErrorFromException(ex);
                return false;
            }
            ]]>
        </Code>
    </Task>
</UsingTask>
0

There are 0 best solutions below