在C#中,我可以在Restsharp中设置一些httpclienthandler属性吗?

时间:2015-06-30 15:42:33

标签: c# rest restsharp dotnet-httpclient

我在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

在restSharp方面。这支持了吗?

1 个答案:

答案 0 :(得分:3)

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