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

时间:2014-09-16 08:37:20

标签: c# windows-phone-8 refit

如果我的用户代理是常量字符串,我可以使用[Headers("User-Agent: Awesome Octocat App")]进行设置。

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

另一个提到的方法如 Dynamic Headers 部分所述,这不是最佳的,因为这是我的全局标题。我不想手动将此标头添加到60+ API方法中。

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

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

1 个答案:

答案 0 :(得分:6)

要在运行时设置默认标头,可以使用DefaultRequestHeaders实例上的HttpClient属性。

这样的事情会起作用:

// 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();
}
相关问题