如何将 C# HTTPClient 与 Windows 凭据一起使用

How to use C# HTTPClient with Windows Credentials

我编写了一个控制台应用程序,它将读取链接的文本文件并使用 HttpClient class 测试它们以检查链接是否存在。当针对 google.com.

等常见链接进行测试时,它在家里工作得非常好

当我 运行 我的工作内联网下的应用程序时,当它检查我们公司 Sharepoint 上的链接时,我得到“禁止”错误,而当它检查 Azure 网站上的链接时,我得到“未经授权”错误。我希望 运行 在我授权的 Windows 台式 PC 下安装它是我工作所需要的一切,但不行。

当我使用 HttpClient 访问链接时,有没有提示如何传递我的网络凭据?

编辑:添加了代码来处理传递的控制台参数(身份验证 cookie 字符串)

using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace linkbot
{
    class Program
    {   
        private static async Task ProcessRepositories(string the_url, string the_cookies)
        {   int the_index=the_url.IndexOf("/",9);
            string base_string=the_url;
            string the_rest="/";
            if (the_index>=0)
            {
                base_string=the_url.Substring(0,the_index);
                the_rest=the_url.Substring(the_index);
            }
            
            try {
                var baseAddress = new Uri(base_string);
                using (var handler = new HttpClientHandler { UseCookies = false })
                using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
                {
                    var message = new HttpRequestMessage(HttpMethod.Get, the_rest);
                    message.Headers.Add("Cookie", the_cookies);
                    var result = await client.SendAsync(message);
                    result.EnsureSuccessStatusCode();
                }
                Write("\n" + the_url + " - WORKED!");
            }
            catch(Exception e )
            {
                Write("\nFailed: " + the_url + "||||||" +e.ToString() );
                //throw e;
            }
        }
        static async Task Main(string[] args)
        {
            if (args.Length<2){
                Console.Write("\n###################\nLinkChecker by Sean J. Miller 2022\n\nusage:\n    linkchecker.exe <linkfile> <cookies>\nwhere <linkfile> contains a text file of fully specified links (URLs) with one link per line.  Example, https://www.google.com\n\nAn output file is generated titled brokenlinks.txt in the same directory where LinkChecker was launched.  <cookies> should be a string such as \"cookie1=value1;cookie2=value2;cookie3=value3;\"\n###################\n\n\n");
                return;
            }
            System.IO.File.Delete("brokenlinks.txt");
            System.IO.File.WriteAllText("brokenlinks.txt", "Last Check Started " + (DateTime.Now).ToString());
            int counter=0;
            int total_lines=TotalLines(@args[0]);
            Console.Write("Started " + (DateTime.Now).ToString() + "\n");
            foreach (string line in System.IO.File.ReadLines(@args[0]))
            {
                Console.Write("Processing Link " + (++counter) + "/" + total_lines + "\n");
                await ProcessRepositories(line, args[1]);
            }
            Console.Write("Finished " + (DateTime.Now).ToString() + "\n");
            Write("\n");
        }

        static void Write(string the_text)
        {
            //Console.Write(the_text);
            try   
            {  
                System.IO.File.AppendAllText("brokenlinks.txt", the_text);
            }
            catch (Exception ex)   
            {  
                throw ex;  
            }
        }

        static int TotalLines(string filePath)
        {
            using (StreamReader r = new StreamReader(filePath))
            {
                int i = 0;
                while (r.ReadLine() != null) { i++; }
                return i;
            }
        }
    }
}

您想将 UseDefaultCredentials 设置为 true 以在您的请求中使用当前的 logged-on 用户凭据。您可以通过像这样实例化 HttpClient 来做到这一点:

private static readonly HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });