如何将System.Net.Http.HttpResponseMessage转换为System.Web.Mvc.ActionResult

时间:2018-10-18 06:37:16

标签: c# asp.net-mvc httpclient actionresult httpresponsemessage

我正在编写一个简单的代理应用程序,该应用程序将获得“ URL地址”(如“ / xController / xMethod”),并通过HttpClient从另一个Web应用程序获取结果并显示结果。

我的方法:

public ActionResult Index(string urlAddress)
{
   var data = "";
   if (Request.ContentLength > 0 && httpRequestMessage != null)
       data = httpRequestMessage.Content.ReadAsStringAsync().Result;

    using (var client = new HttpClient())
    {
      // fill header and set target site url 

      // Make Post Data
      var buffer = System.Text.Encoding.UTF8.GetBytes(data);
      var byteContent = new ByteArrayContent(buffer);
      if (!String.IsNullOrWhiteSpace(Request.ContentType) && !String.IsNullOrEmpty(Request.ContentType))
           byteContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue(Request.ContentType);

       // make query string ....

       // sending request to target site         
       HttpResponseMessage response = null;
       if (Request.HttpMethod.ToUpper() == "POST")
             response = client.PostAsync(urlAddress + queryString, byteContent).Result;
       else
             response = client.GetAsync(any + queryString).Result;

    // My Problem is in here....
    return ....;              
  }
}

我想在浏览器中显示我的请求,当响应是文件时,浏览器下载内容,当响应是Json时显示为Json,依此类推。

(例如) 我知道何时要显示HTML。我正在使用:

ActionResult x = new ContentResult()
                {
                    Content = response.Content.ReadAsStringAsync().Result,
                    ContentType = response.Content.Headers.ContentType.MediaType
                };
                return x;

或当我想使用JsonActionResult作为html返回或使用FileContentResult在File中返回时,但是我想要将所有HttpResponseMessage转换为Best ActionResult类的快速可靠的解决方案

1 个答案:

答案 0 :(得分:1)

我建议您使用IHttpActionResult作为Web API 2中引入的操作结果。 您可以使用ResponseMessage方法将HttpResponseMessage转换为IHttpActionResult 来自ApiController。因此,您的控制器应继承ApiController。

我的解决方案:

 public class TrainController : ApiController
{
    public IHttpActionResult SomeAction()
    {
        HttpResponseMessage responseMsg =
            new 
            HttpResponseMessage(HttpStatusCode.RedirectMethod);

        /*responseMsg = your implementation*/

        IHttpActionResult response = this.ResponseMessage(responseMsg);
        return response;
    }
}