将HttpWebResponse转换为HttpResponseMessage

时间:2014-07-02 18:24:14

标签: c# asp.net-mvc asp.net-mvc-5.1

我在asp.net WebAPI控制器中执行以下操作:

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 个答案:

答案 0 :(得分: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;