我在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方面。这支持了吗?
答案 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);