【问题标题】:In C#, can I set some httpclienthandler properties in Restsharp?在 C# 中,我可以在 Restsharp 中设置一些 httpclienthandler 属性吗?
【发布时间】:2015-06-30 15:42:32
【问题描述】:

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

这是我当前的代码:

 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

在其余锐利的一面。支持吗?

【问题讨论】:

  • 查看更新的答案,如果有帮助的话。
  • 为什么不直接将反序列化器移植到 HttpClient 上使用?

标签: c# rest restsharp dotnet-httpclient


【解决方案1】:

如果您想使用基本 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);

【讨论】:

  • 谢谢。 .关于设置的任何想法:AllowAutoRedirect
猜你喜欢
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多