2013-03-08 112 views
2

我想要做的 - 我猜 - 是使用API​​作为代理。它与Fiddler合作,并有这个想法。c#可以API返回HttpWebResponse

我有一个网站,并希望显示另一个iframe。但我需要删除'不公开'标题来做到这一点。

所以计划是: 从我的网站发送一个url字符串到API,API向该网址发出请求,获取响应,并且不保存页面只是改变一些标题并回应我的网站。

问题: 它不断返回一个json。我试图以字符串形式返回html代码,但是我的网站不会将其呈现到iframe中。

这是我的代码。

public class ProductsController : ApiController 
{ 
    public HttpWebResponse GetProductsByCategory(string url, int edit) 
    {    
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
     request.Method = WebRequestMethods.Http.Get; 
     request.ContentType = "text/html"; 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
     // 
     if (edit == 1) 
     {        
      response.Headers.Set("Content-Disposition", ""); 
      response.Headers.Set("X-Download-Options", "");    
     } 
     response.Headers.Set("Content-Type", "text/html"); 
     response.Headers.Set("APIflag", "Hi!"); 

     Stream theHTML = response.GetResponseStream(); 
     StreamReader objReader = new StreamReader(theHTML); 
     string myHTML = objReader.ReadToEnd(); 

     System.Diagnostics.Debug.WriteLine("url was: "+url); //is OK 
     System.Diagnostics.Debug.WriteLine("edit flag was: " +edit); //is OK 
     System.Diagnostics.Debug.WriteLine(myHTML); //is OK 

     return response; 
    } 
} 

回答

3

这样,它的工作

public class ProductsController : ApiController 
{  
    public HttpResponseMessage GetProductsByCategory(string url) 
    {   
     HttpResponseMessage theResponse = null; 
     // init a wep api Client 
     var myClient = new HttpClient(); 
     var theTask = myClient.GetAsync(url).ContinueWith((lamdaObj) => 
     { 
      theResponse = lamdaObj.Result; 
     }); 
     // wait for task to complete. Not really async, is it?! 
     theTask.Wait(); 
     // remove annoying header 
     theResponse.Content.Headers.Remove("Content-Disposition"); 
     return theResponse; 
    } 
} 

}

+0

要容易得多,比我在做什么,包括“恼人的头”你说的那样,我需要。谢谢! – Vince 2015-11-06 21:08:09