Last active
September 10, 2020 18:04
-
-
Save Warrenn/5203e77eecac6a8f1985b30abc24381c to your computer and use it in GitHub Desktop.
Add custom client interceptions for any client WebRequest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// <configuration> | |
// <system.net> | |
// <webRequestModules> | |
// <add prefix="http" | |
// type="UserAgentRequestCreator, namespace, Version=1.0.0.0, | |
// Culture=neutral, PublicKeyToken=9999999999999999" | |
// /> | |
// </webRequestModules> | |
// </system.net> | |
// </configuration> | |
public class UserAgentRequestCreator : IWebRequestCreate | |
{ | |
public const string UserAgentKey = "HTTP_WEB_REQUEST_USER_AGENT"; | |
private static string _defaultUserAgentName = new Lazy<string>(() => | |
{ | |
var agentValue = Environment.GetEnvironmentVariable(UserAgentKey); | |
return !string.IsNullOrWhiteSpace(agentValue) ? agentValue : ConfigurationManager.AppSettings[UserAgentKey]; | |
}).Value; | |
private readonly string _userAgentName; | |
public UserAgentRequestCreator() : this(_defaultUserAgentName) { } | |
public UserAgentRequestCreator(string userAgentName) | |
{ | |
_userAgentName = userAgentName; | |
} | |
public static void SetDefaultUserAgent(string defaultValue) | |
{ | |
_defaultUserAgentName = defaultValue; | |
} | |
public static void RegisterUserAgent(string url, string agentName) | |
{ | |
WebRequest.RegisterPrefix(url, new UserAgentRequestCreator(agentName)); | |
} | |
#region Implementation of IWebRequestCreate | |
public WebRequest Create(Uri uri) | |
{ | |
if (!(WebRequest.CreateDefault(uri) is HttpWebRequest httpWebRequest)) | |
throw new InvalidOperationException("The URI prefix is not recognized."); | |
if (string.IsNullOrWhiteSpace(_userAgentName)) return httpWebRequest; | |
var methodInfo = typeof(WebHeaderCollection).GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic); | |
methodInfo.Invoke(httpWebRequest.Headers, new object[] { "User-Agent", _userAgentName }); | |
return httpWebRequest; | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment