【问题标题】:How to add a static authorization header with refit in xamarin.forms?如何在 xamarin.forms 中添加带有 refit 的静态授权标头?
【发布时间】:2019-11-14 00:27:34
【问题描述】:

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

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

然后我得到了一个静态的 Config 类:

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,但这并不能说服我,因为他/她在他/她的 api 定义中放置了一个动态标题。 也许问题出在多个标题中?

【问题讨论】:

    标签: c# xamarin.forms refit


    【解决方案1】:

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

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

    【讨论】:

    • 并使用 OAuth 令牌 授权grant_type=client_credentials &amp;client_id=example_client_id &amp;client_secret=example_client_secret &amp;scope=user.read ?
    猜你喜欢
    • 2017-10-04
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2020-09-17
    • 2017-05-19
    相关资源
    最近更新 更多