代码之家  ›  专栏  ›  技术社区  ›  JohnPan

c#可以让API返回HttpWebResponse

  •  3
  • JohnPan  · 技术社区  · 12 年前

    我想我要做的是使用API作为代理。它与Fiddler合作,产生了这个想法。

    我有一个网站,希望在iframe中显示另一个。但我需要删除“不打开”标题才能做到这一点。

    因此,计划是: 从我的站点向API发送一个url字符串,API向该url发出请求,获取响应,在不保存页面的情况下,只需更改几个标题并回复到我的网站。

    问题: 它不断返回一个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;
        }
    }
    
    2 回复  |  直到 12 年前
        1
  •  3
  •   JohnPan    12 年前

    这样就起作用了

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

    }

        2
  •  0
  •   Jras    12 年前

    您可能需要查看ASP.net web api。您可以使用位于的WCF HTTP堆栈执行此操作 http://wcf.codeplex.com/ 。它已包含在ASP.net web api中。 http://www.asp.net/web-api