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

1

6

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

Desilva answered 18/10, 2018 at 6:37 Comment(0)
B
6

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;
    }
}
Bombsight answered 18/10, 2018 at 7:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.