i'm trying to add a static authorization Header with basic authentication, but when i do the request, the server response is negative. So, i tried to add it in this way:
[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);
}
Then i got a static Config 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);
But it doesn't work and the requests are not authorized. I follow this question too: Refit and authorization header, but it doesn't convince me, because he/she put a dynamic header in his/her api definition. Maybe the problem is in the multiple headers?
Since your authorization header never changes, you don't really need to use AuthorizationHeaderValueGetter
(which is intended to be used for more dynamic auth scenarios). Instead, just use the DefaultRequestHeaders
dictionary on your HttpClient
:
var client = new HttpClient
{
BaseAddress = new Uri("https://example.com"),
DefaultRequestHeaders =
{
{"Authorization", $"Basic {authHeader}"}
}
};
var api = RestService.For<IYourApi>(client);