Setting “User-Agent” HTTP header in ClientWebSocket

前端 未结 2 1545
南旧
南旧 2021-01-18 13:29

I need to set the \"User-Agent\" HTTP header in a ClientWebSocket object, but it is not possible. Although there is a ClientWebSocket.SetRequestHeader(hea

2条回答
  •  情话喂你
    2021-01-18 14:05

        //use reflection to remove IsRequestRestricted from headerInfo hash table
        Assembly a = typeof(HttpWebRequest).Assembly;
        foreach (FieldInfo f in a.GetType("System.Net.HeaderInfoTable").GetFields(BindingFlags.NonPublic | BindingFlags.Static))
        {
            if (f.Name == "HeaderHashTable")
            {
                Hashtable hashTable = f.GetValue(null) as Hashtable;
                foreach (string sKey in hashTable.Keys)
                {
    
                    object headerInfo = hashTable[sKey];
                    //Console.WriteLine(String.Format("{0}: {1}", sKey, hashTable[sKey]));
                    foreach (FieldInfo g in a.GetType("System.Net.HeaderInfo").GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
                    {
    
                        if (g.Name == "IsRequestRestricted")
                        {
                            bool b = (bool)g.GetValue(headerInfo);
                            if (b)
                            {
                                g.SetValue(headerInfo, false);
                                Console.WriteLine(sKey + "." + g.Name + " changed to false");
                            }
    
                        }
                    }
    
                }
            }
        } 
    

    More info here: Cannot set some HTTP headers when using System.Net.WebRequest

提交回复
热议问题