Search code examples
c#windows-phone-8refit

How do I set the User-Agent at runtime with refit?


If my user agent is a constant string, I can use [Headers("User-Agent: Awesome Octocat App")] to set it.

However, My user agent is generated by a method (because it includes the device and OS version), which means I can't put it inside the Headers attribute.

The other mentioned method is as described in the Dynamic Headers section, which is less than optimal since this is a global header for me. I'd rather not manually add this header to the 60+ API methods.

How would I go about doing this? Is it a supported scenario? Using a custom HttpClient is an acceptable solution (if possible).

I'm also open to other similar products if you know of any that may serve my purpose.


Solution

  • To set default headers at runtime, you can use the DefaultRequestHeaders property on the HttpClient instance.

    Something like this will work:

    // 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();
    }