11

I have the following action in an asp.net WebAPI controller:

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 ???;
}

How can I convert the HttpWebResponse into an HttpResponseMessage?

svick
  • 236,525
  • 50
  • 385
  • 514
Metaphor
  • 6,157
  • 10
  • 54
  • 77

1 Answers1

5

The best way to transform HttpWebResponse in HttpResponseMessage is create a new HttpResponseMessage :

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

Rui Caramalho
  • 455
  • 8
  • 16
Igor Monteiro
  • 933
  • 1
  • 11
  • 29
  • 2
    What about headers that were part of responseApi? Is there any need to keep any of those? Is there a generic way to handle this for all content types instead of hardcoding it to application/json? – NStuke Nov 11 '16 at 07:10
  • This is in case of a successful request (HttpStatusCode.OK). How can I parse statusCode and reasonPhrase out of a ´HttpWebResponse´ if request is unsuccessful? – Ozkan Mar 04 '22 at 09:01