简体   繁体   中英

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 .

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

尝试:

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

You can try like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM