如何在 xamarin.forms 中添加静态授权 header 并进行改装?

How to add a static authorization header with refit in xamarin.forms?

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

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

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

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

但是不起作用,请求未被授权。 我也关注这个问题:Refit and authorization header,但它并不能说服我,因为 he/she 在 his/her api 定义中放置了动态 header。 也许问题出在多个 headers?

由于您的授权 header 永远不会改变,您实际上不需要使用 AuthorizationHeaderValueGetter(它旨在用于更动态的身份验证场景)。相反,只需在 HttpClient:

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

var api = RestService.For<IYourApi>(client);