Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can convert System.Net.Http.HttpResponseMessage to System.Web.Mvc.ActionResult

I'm Writing simple proxy application which get "URL Address" like "/xController/xMethod" and get result from another web application by HttpClient and show result.

My Method:

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

i want to show my request in browser and when response was file the browser download the content and when response is Json show as Json and so on.

(for example) i know when i want to show HTML . i am using :

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

or when i want return as html using JsonActionResult or in File using FileContentResult , but i want fast and reliable solution to convert any HttpResponseMessage to Best ActionResult Class

like image 890
MABDigital Avatar asked Oct 16 '22 11:10

MABDigital


1 Answers

I suggest you to use IHttpActionResult as action result which are introduced in Web API 2. You can convert HttpResponseMessage to IHttpActionResult using the method ResponseMessage from ApiController. so , your controller should inherit the ApiController.

My solution :

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

        /*responseMsg = your implementation*/

        IHttpActionResult response = this.ResponseMessage(responseMsg);
        return response;
    }
}
like image 130
Njara Liantsoa Avatar answered Oct 31 '22 16:10

Njara Liantsoa