1

我正在尝试添加具有基本身份验证的静态授权标头,但是当我发出请求时,服务器响应是否定的。所以,我尝试以这种方式添加它:

[Headers("Authorization: Basic","Content-Type: application/x-www-form-urlencoded" )]

public interface IRouteApi
{
    [Post("/getRoute?dtxIni={Ini}&dtxFin={Fin}")]
    Task<HttpResponseMessage> getPathInfo(int Ini, int Fin);
}

然后我得到了一个静态配置类:

public static class Config
{
    public static string ApiUrl = "http://www2.baseUrl.it/Base";
    static string username = "aaa";
    static string password = "bbb";
    public static string authHeader = 
    Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

    public static RefitSettings refitSettings = new RefitSettings()
    {
        AuthorizationHeaderValueGetter = () => Task.FromResult(authHeader)
    };
}
RestService.For<T>(client,Config.refitSettings);

但它不起作用,请求未经授权。我也关注这个问题:改装和授权标头,但这并不能说服我,因为他/她在他/她的 api 定义中放置了一个动态标头。也许问题出在多个标题中?

4

1 回答 1

5

由于您的授权标头永远不会更改,因此您实际上不需要使用AuthorizationHeaderValueGetter(旨在用于更动态的身份验证场景)。相反,只需使用DefaultRequestHeaders您的字典HttpClient

var client = new HttpClient
{
    BaseAddress = new Uri("https://example.com"),
    DefaultRequestHeaders = 
    {
        {"Authorization", $"Basic {authHeader}"}
    }
};

var api = RestService.For<IYourApi>(client);
于 2019-09-13T06:18:58.990 回答