在C#中,我可以在Restsharp中设置一些httpclienthandler属性吗?
作者:互联网
我在使用HTTPClient的C#中具有以下代码,并且尝试迁移到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
在restSharp方面.支持吗?
解决方法:
如果要使用基本HTTP身份验证,则需要为RestSharp提供以下基本身份验证信息.
_client = new RestClient { BaseUrl =new Uri(myUrl) };
_client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
要使用Windows身份验证:
Update:
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);
标签:restsharp,rest,dotnet-httpclient,c 来源: https://codeday.me/bug/20191120/2041221.html