我在 C# 中有以下使用 HTTPClient 的代码,我正在尝试迁移到 RestSharp 以利用漂亮的反序列化代码

这是我当前的代码:

 var httpClient = new HttpClient(new HttpClientHandler()
        {
            UseDefaultCredentials = true,
            AllowAutoRedirect = false
        });

 var response = httpClient.GetStringAsync(myUrl).Result;

这是使用restsharp的等效代码:
 _client = new RestClient { BaseUrl =new Uri(myUrl) };
 var request = new RestRequest { Method = method, Resource = "/project", RequestFormat = DataFormat.Json };
 var response = _client.Execute(request);

但我不知道如何设置
 UseDefaultCredentials = true


 AllowAutoRedirect = false

在其余锋利的一面。这是支持的吗?

最佳答案

如果您想使用基本 HTTP 身份验证,您需要为 RestSharp 提供如下基本身份验证信息。

 _client = new RestClient { BaseUrl =new Uri(myUrl) };
_client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");

要使用 Windows 身份验证:


    const Method httpMethod = Method.GET;
    string BASE_URL = "http://localhost:8080/";

    var client = new RestClient(BASE_URL);
    // This property internally sets the AllowAutoRedirect of Http webrequest
    client.FollowRedirects = true;
    // Optionally you can also add the max redirects
    client.MaxRedirects = 2;

    var request = new RestRequest(httpMethod)
    {
        UseDefaultCredentials = true
    };

    client.Execute(request);

关于c# - 在 C# 中,我可以在 Restsharp 中设置一些 httpclienthandler 属性吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31142740/

10-11 22:32