Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from HttpResponseMessage to IActionResult in .NET Core

I'm porting over some code that was previously written in .NET Framework to .NET Core.

I had something like this:

HttpResponseMessage result = await client.SendAync(request);
if (result.StatusCode != HttpStatusCode.OK)
{
    IHttpActionResult response = ResponseMessage(result);
    return response;
}

The return value of this function is now IActionResult.

How do I take the HttpResponseMessage result object and return an IActionResult from it?

like image 200
noblerare Avatar asked Aug 01 '18 20:08

noblerare


2 Answers

You can return using hardset status codes like Ok(); or BadRequest();

Or return using a dynamic one using

StatusCode(<Your status code number>,<Optional return object>);

This is using Microsoft.AspNetCore.Mvc

Below is this.StatusCode spelled out a little more:

/* "this" comes from your class being a subclass of Microsoft.AspNetCore.Mvc.ControllerBase */
StatusCodeResult scr = this.StatusCode(200);
/* OR */
Object myObject = new Object();
ObjectResult ores = this.StatusCode(200, myObject);
return scr; /* or return ores;*/
like image 85
Lyco Avatar answered Sep 17 '22 12:09

Lyco


You should be able to migrate your existing code into ASP.NET Core 2.x by using Microsoft.AspNetCore.Mvc.WebApiCompatShim nuget package.

Then you may do:

return new ResponseMessageResult(result);

Or, as an alternative, you may inherit your Controller from ApiController and leave your code as is:

public class MyController : ApiController 
{
    public IActionResult Get()
    {
        // other code...
        HttpResponseMessage result = await client.SendAync(request);
        if (result.StatusCode != HttpStatusCode.OK)
        {
            IActionResult response = ResponseMessage(result);
            return response;
        }
        // other code...
    }    
}

More information inside the official documentation

like image 22
Federico Dipuma Avatar answered Sep 17 '22 12:09

Federico Dipuma