2014-07-02 82 views
9

我曾在一個asp.net的WebAPI控制器下列行動:談到HttpWebResponse到HttpResponseMessage

public HttpResponseMessage GetCBERSS(string Site, string File, string User, string Password) 
{ 
    string URLString = string.Format("https://{0}.rss.mycompany.com/{1}", Site, File); 
    Uri uri = new Uri(URLString); 
    CredentialCache cache = new CredentialCache(); 
    cache.Add(uri, "Basic", new NetworkCredential(User, Password)); 
    WebRequest r = WebRequest.Create(uri); 
    r.Credentials = cache; 
    r.ContentType = "application/rss+xml"; 
    IgnoreBadCertificates(); 
    HttpWebResponse result = (HttpWebResponse)r.GetResponse(); 
    return ???; 
} 

我怎麼能轉換HttpWebResponse成HttpResponseMessage?

+1

看到這個對方回答:http://stackoverflow.com/a/11125737/507793 – Matthew

回答

4

在HttpResponseMessage改造HttpWebResponse的最好方法是創建一個新的HttpResponseMessage:

 var response = new HttpResponseMessage(HttpStatusCode.OK); 

      using (var responseApi = (HttpWebResponse)request.GetResponse()) 
      {      
       using (var reader = new StreamReader(responseApi.GetResponseStream())) 
       { 
        var objText = reader.ReadToEnd(); 
        response.Content = new StringContent(objText, Encoding.UTF8, "application/json"); 
       } 
      } 
      return response; 
+0

那麼,那些人的部分標題responseApi?有沒有必要保留這些?有沒有一種通用的方式來處理所有內容類型,而不是硬編碼到application/json? – NStuke