2013-02-11 108 views
1

我有一個C#Windows窗體應用程序,我正在使用它來連接到一個用於製作Web請求的服務器。我需要做的是讓用戶通過首選項設置某些屬性,並將這些屬性動態添加到WebRequest。向HttpWebRequest動態添加屬性

一樣,如果我有一個配置文件與條目 - >

<Properties> 
     <Property name="User-Agent" value="Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" /> 
     <Property name="KeepAlive" value="true" /> 
</Properties> 

現在我想將值綁定到WebRequest的屬性。

Uri serverURL = new Uri("http://MyServer:8080/MyPage.jsp"); 
     HttpWebRequest wreq = WebRequest.Create(serverURL) as HttpWebRequest; 
     XmlDocument xmldoc = new XmlDocument(); 
     xmldoc.Load(<Path of Config>); 
     XDocument xDoc = XDocument.Parse(xmldoc.InnerXml); 
     Dictionary<string, string> propdict = new Dictionary<string, string>(); 
     foreach (var section in xDoc.Root.Elements("Property")) 
     { 
      propdict.Add(section.Attribute("name").Value, section.Attribute("value").Value); 
     }    

     string key = string.Empty, value = string.Empty; 
     foreach (var item in propdict) 
     { 
      //... add the properties to wreq 
     } 

有人可以讓我知道這可以實現嗎?

感謝

蘇尼爾Jambekar

+0

'if(name ==「User-Agent」){request.UserAgent = value; }'? – dtb 2013-02-11 12:58:50

回答

2

這聽起來像你想添加HTTP請求頭,在這種情況下:

wreq.Headers.Add(headerName, headerValue); 

但是! IIRC,許多頭屬於特例,例如,它可以拒絕接受用戶代理的頭,而是堅持你設置:

wreq.UserAgent = userAgentString; 
wreq.KeepAlive = setKeepAlive; 

所以,你可能需要:

foreach(var item in propdict) { 
    switch(item.Name) { 
     case "User-Agent": 
      wreq.UserAgent = item.Value; 
      break; 
     case "KeepAlive": 
      wreq.KeepAlive = bool.Parse(item.Value); 
      break; 
     // ... etc 

     default: 
      wreq.Headers.Add(item.Name, item.Value); 
      break; 
    } 
} 

(你也許想考慮大小寫敏感度)

+0

非常感謝Marc ....這正是我寫的代碼,但是我對它不滿意。我想如果有可以動態應用的東西。 User-Agent和KeepAlive不工作,如果我通過標題。 – Sunil 2013-02-12 03:34:24