5

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.

copolii
  • 14,208
  • 10
  • 51
  • 80
  • As per this link (https://github.com/paulcbetts/refit), it should be possible. Am not able to understand clear usage of that. Maybe some more explanation will help to give answer. – Sanket Tarun Shah Sep 16 '14 at 08:42
  • Yeah I saw that too, I added a bit to the question explaining why that's not an ideal solution. – copolii Sep 16 '14 at 08:46

1 Answers1

8

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();
}
Bennor McCarthy
  • 11,415
  • 1
  • 49
  • 51