简体   繁体   中英

In C#, can I set some httpclienthandler properties in Restsharp?

I have the following code in C# that uses HTTPClient and I am trying to migrate to RestSharp to leverage the nice Derserialization code

here is my current code:

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

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

Here is the equivalent code using restsharp:

 _client = new RestClient { BaseUrl =new Uri(myUrl) };
 var request = new RestRequest { Method = method, Resource = "/project", RequestFormat = DataFormat.Json };
 var response = _client.Execute(request);

but I can't figure out how to set

 UseDefaultCredentials = true

and

 AllowAutoRedirect = false

on the restSharp side. Is this supported?

You need provide the basic authentication information like below for RestSharp if you want to use the Basic HTTP authentication.

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

To use the windows authentication:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM