'How to set HttpResponse to HttpResponseMessage in Web API

I have a asp.net web API application hosted using OWIN. The web API application uses an external library which depends on System.Web and writes its response on System.Web.Response object. I have set a dummy object to HttpContext.Current and after that the I expect the external library would set the response at HttpRequest. Then I need to know how I could transfer the result from HttpRequest to HttpRequestMessage so that the web API method could process the result.

Here is some sample code:

public HttpResponseMessage GetTest()
{
    HttpResponseMessage responseMessage = new HttpResponseMessage();

    HttpResponse httpResponse = new HttpResponse(new StreamWriter(new MemoryStream()));
    httpResponse.Write("From HttpResponse");

    return responseMessage;
}

I have written some text using the HttpResponse.Write() method, now I need to move the result from HttpResponse to HttpResponseMessage.



Solution 1:[1]

I believe what you are looking for is IHttpActionResult see link: https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results

Here is an example of how to create a HttpResponseMessage:

public IHttpActionResult Get()
{
   HttpResponseMessage responseMessage = "From HttpResponse";
   return new ResponseMessageResult(responseMessage);
}

Solution 2:[2]

Try:

return Request.CreateResponse(HttpStatusCode.OK, "{data to return here}")

Solution 3:[3]

You can try like below:

   if (yourCondition)  
   {  
      return Request.CreateResponse<Employee>(HttpStatusCode.OK, obj);  
   }  
   else  
   {  
      return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");  
   }  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hanane Moshe
Solution 2 Alex
Solution 3 Abdus Salam Azad