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?
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;*/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With