如何在运行时使用refit设置User-Agent?

cop*_*lii 4 c# windows-phone-8 refit

如果我的用户代理是一个常量字符串,我可以[Headers("User-Agent: Awesome Octocat App")]用来设置它.

但是,我的用户代理是由方法生成的(因为它包含设备和操作系统版本),这意味着我无法将其放在Headers属性中.

另一个提到的方法是动态标题部分中描述的,它不是最优的,因为这是我的全局标题.我宁愿不手动将此标头添加到60+ API方法中.

我该怎么做呢?它是受支持的场景吗?使用自定义HttpClient是可接受的解决方案(如果可能).

如果您知道任何可能符合我目的的产品,我也会对其他类似产品持开放态度.

Ben*_*thy 6

要在运行时设置默认标头,可以DefaultRequestHeadersHttpClient实例上使用该属性.

这样的东西会起作用:

// This example uses http://httpbin.org/user-agent, 
// which just echoes back the user agent from the request.
var httpClient = new HttpClient
{
    BaseAddress = new Uri("http://httpbin.org"), 
    DefaultRequestHeaders = {{"User-Agent", "Refit"}}
};
var service = RestService.For<IUserAgentExample>(httpClient);
var result = await service.GetUserAgent(); // result["user-agent"] == "Refit"

// Assuming this interface
public interface IUserAgentExample
{
    [Get("/user-agent")]
    Task<Dictionary<string, string>> GetUserAgent();
}
Run Code Online (Sandbox Code Playgroud)