2014-07-02 8 views
9

ich die folgende Aktion in einem asp.net WebAPI Controller haben:HttpWebResponse Drehen in eine 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 ???; 
} 

Wie kann ich die HttpWebResponse in eine HttpResponseMessage konvertieren?

+1

diese andere Antwort Siehe: http://stackoverflow.com/a/11125737/507793 – Matthew

Antwort

4

Der beste Weg, HttpWebResponse in HttpResponseMessage zu verwandeln ist eine neue HttpResponseMessage erstellen:

 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

Was Header, die Teil waren von AntwortApi? Müssen Sie irgendwelche davon behalten? Gibt es eine generische Möglichkeit, dies für alle Inhaltstypen zu handhaben, statt sie in application/json zu kodieren? – NStuke