如何使用 RestSharp 为新的 RestClient 设置身份验证器

Spo*_*oky 10 .net c# restsharp asp.net-core

使用 .net 6.0 和 RestSharp 110.0.1 当我按照 RestSharp 文档(下面链接)中的示例进行操作时,我收到错误“RestClient.Authenticator 无法分配给 - 它是只读的。”

RestSharp 文档 GitHub Gist 获取文档代码

public class WebInteractionsAuthenticator : AuthenticatorBase {
    readonly string _baseUrl;
    readonly string _clientId;
    readonly string _clientSecret;

    public WebInteractionsAuthenticator(string baseUrl, string clientId, string clientSecret) : base("") {
        _baseUrl      = baseUrl;
        _clientId     = clientId;
        _clientSecret = clientSecret;
    }

    protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken) {
        Token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
        return new HeaderParameter(KnownHeaders.Authorization, Token);
    }

    async Task<string> GetToken() {
        var options = new RestClientOptions(_baseUrl);
        using var client = new RestClient(options) {

[tag:// ERROR IS AT FOLLOWING LINE]

            Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret),
        };

        var request = new RestRequest("oauth2/token")
            .AddParameter("grant_type", "client_credentials");
        var response = await client.PostAsync<TokenResponse>(request);
        return $"{response!.TokenType} {response!.AccessToken}";
    }
}
Run Code Online (Sandbox Code Playgroud)

Visual Studio 中的错误图像

我尝试寻找替代方案,但找不到任何解决此问题的方法。

Bra*_*ang 15

正如 Obsolete 所说,我们应该使用 RestClientOptions.Authenticator 来代替,所以我建议您可以尝试以下代码:

var options = new RestClientOptions();

options.Authenticator = new HttpBasicAuthenticator("","");

using var client = new RestClient(options)
{
     
};
Run Code Online (Sandbox Code Playgroud)