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

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.