Convert from HttpResponseMessage to IActionResult in .NET Core
Asked Answered
V

6

32

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?

Vesicate answered 1/8, 2018 at 20:17 Comment(6)
Are you running .NET Core 2.1?Repand
How could we help you without knowing what ResponseMessage does?Theatricalize
@FedericoDipuma ResponseMessage is from Asp.Net Web API 2 ApiController that converted HttpResponseMessage to IHttpActionResult. OP is porting previous code over to current version.Crosby
@FedericoDipuma ResponseMessage is a function part of System.Web.Http library. It just creates a ResponseMessageResult from your specified HttpResponseMessage.Northerner
Didn't remember about that method at all. Thank you for the clarification @CrosbyTheatricalize
it does not look like there is a built in way to do what it is you are requesting. You always build your own extension method to extract the necessary data and return an appropriate response.Crosby
N
17

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;*/
Northerner answered 1/8, 2018 at 21:11 Comment(2)
Could you add the fully qualified name? Or the "using" statement? Thank you.Teryn
@Teryn sureNortherner
T
16

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 one of the following:

1 use ResponseMessageResult

return new ResponseMessageResult(result);

2 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

Theatricalize answered 1/8, 2018 at 21:19 Comment(5)
is ApiController available in .Net Core? i thought in .Net core its just one Controller base class?Clad
@Clad as stated in the answer, ApiController is a compatibility class you get when using Microsoft.AspNetCore.Mvc.WebApiCompatShim nuget package.Theatricalize
What is missing in this response is that you have to enable the WebApi compatibility layer by calling services.AddMvc().AddWebApiConventions(); in ConfigureServices function of the server Startup class. (Otherwise, the server will just try to serialize the ResponseMessage object as JSON.)Giusto
is that possible for razor page?Shipway
"as stated in the answer" - That's not what your answer states though. Your answer states "Use WebApiCompatShim to do X, Or, as an alternative Use ApiController to do Y" which suggests you don't need the WebApiCompatShim for the ApiController. If that isn't the case then you may want to reword it.Imperator
A
7

I had similar issue porting code to .net6 where HttpResponseMessage is not a thing for controller anymore. Those are being returned as regular objects no matter what. Event if you return HttpResponseMessage with 500 status code, you'll get everything wrapped into 200 response code result. So I end up with a extention method like this:

public static async Task<ContentResult> ToContentResultAsync(this 
HttpResponseMessage responseMessage, string contentType)
        {
            var contentRes = new ContentResult();
            contentRes.StatusCode = (int)responseMessage.StatusCode;
            contentRes.Content = await responseMessage.Content.ReadAsStringAsync();
            contentRes.ContentType = contentType;
            return contentRes;
        }

And using it inside controller action like:

[HttpPut, Route("some-route")]       
public async Task<IActionResult> SomeAction(...)
{
    var someClient = new HttpClient();           
        
    var res = await client.PutAsync($"api/urlHere");  

    // ... more stuff happening here       
                 
    return await res.ToContentResultAsync("application/json");           
      
}

The method above is designed for application/json content, but you can tune it for any content and object type depending on your needs.

Hope this helps anyone dealing with .net core or .net6 migrations.

Ardor answered 9/12, 2022 at 16:19 Comment(2)
Why does contentType need to be passed in instead of reading it from responseMessage? contentRes.ContentType = responseMessage.Content.Headers.ContentType.MediaType;?Mvd
Good point, I believe for some reason contentType was always set to null in the original response, if I remember correctly. Agree this might not be the case for every scenario, I should probably edit the response and mention this to bring more clarity.Ardor
T
6

This is much easier to accomplish in .NET v5 (erstwhile .NET Core v5). The ControllerBase class which is found in Microsoft.AspNetCore.Mvc.Core DLL contains scores of methods which return objects which inherit from IActionResult. IActionResult is the replacement for HttpResponseMessage. I ported below web API method which used to return a file. It was based on .NET Framework v4.6.

[HttpGet]
public IHttpActionResult GetFooBar()
{
    var fileContentByteArray = foodBarDomainService.GetExeByteArray();
    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(fileContentByteArray)
    };
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "FooBar.exe"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return ResponseMessage(result);
}

Here is the code which I ported to .NET v5:

[HttpGet("GetFooBar", Name = "GetFooBar")]
public IActionResult GetFooBar(string token)
{
    var fileContentByteArray = foodBarDomainService.GetExeByteArray();
    return File(fileContentByteArray, "application/octet-stream", "FooBar.exe");
}

Here is the complete list of all the methods which return a class that implements IActionResult interface to serve a specific purpose:

public virtual AcceptedResult Accepted(Uri uri, [ActionResultObjectValue] object value);
public virtual AcceptedResult Accepted(string uri, [ActionResultObjectValue] object value);
public virtual AcceptedResult Accepted(Uri uri);
public virtual AcceptedResult Accepted([ActionResultObjectValue] object value);
public virtual AcceptedResult Accepted();
public virtual AcceptedResult Accepted(string uri);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName, object routeValues, [ActionResultObjectValue] object value);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, object routeValues, [ActionResultObjectValue] object value);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, [ActionResultObjectValue] object value);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName, [ActionResultObjectValue] object routeValues);
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName);
public virtual AcceptedAtRouteResult AcceptedAtRoute(object routeValues, [ActionResultObjectValue] object value);
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName, object routeValues, [ActionResultObjectValue] object value);
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName, object routeValues);
public virtual AcceptedAtRouteResult AcceptedAtRoute([ActionResultObjectValue] object routeValues);
public virtual BadRequestResult BadRequest();
public virtual BadRequestObjectResult BadRequest([ActionResultObjectValue] object error);
public virtual BadRequestObjectResult BadRequest([ActionResultObjectValue] ModelStateDictionary modelState);
public virtual ChallengeResult Challenge(params string[] authenticationSchemes);
public virtual ChallengeResult Challenge();
public virtual ChallengeResult Challenge(AuthenticationProperties properties);
public virtual ChallengeResult Challenge(AuthenticationProperties properties, params string[] authenticationSchemes);
public virtual ConflictResult Conflict();
public virtual ConflictObjectResult Conflict([ActionResultObjectValue] object error);
public virtual ConflictObjectResult Conflict([ActionResultObjectValue] ModelStateDictionary modelState);
public virtual ContentResult Content(string content);
public virtual ContentResult Content(string content, MediaTypeHeaderValue contentType);
public virtual ContentResult Content(string content, string contentType, Encoding contentEncoding);
public virtual ContentResult Content(string content, string contentType);
public virtual CreatedResult Created(Uri uri, [ActionResultObjectValue] object value);
public virtual CreatedResult Created(string uri, [ActionResultObjectValue] object value);
public virtual CreatedAtActionResult CreatedAtAction(string actionName, string controllerName, object routeValues, [ActionResultObjectValue] object value);
public virtual CreatedAtActionResult CreatedAtAction(string actionName, object routeValues, [ActionResultObjectValue] object value);
public virtual CreatedAtActionResult CreatedAtAction(string actionName, [ActionResultObjectValue] object value);
public virtual CreatedAtRouteResult CreatedAtRoute(object routeValues, [ActionResultObjectValue] object value);
public virtual CreatedAtRouteResult CreatedAtRoute(string routeName, object routeValues, [ActionResultObjectValue] object value);
public virtual CreatedAtRouteResult CreatedAtRoute(string routeName, [ActionResultObjectValue] object value);
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual VirtualFileResult File(string virtualPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual VirtualFileResult File(string virtualPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, bool enableRangeProcessing);
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName);
public virtual VirtualFileResult File(string virtualPath, string contentType, bool enableRangeProcessing);
public virtual VirtualFileResult File(string virtualPath, string contentType);
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual FileStreamResult File(Stream fileStream, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual FileStreamResult File(Stream fileStream, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, bool enableRangeProcessing);
public virtual FileStreamResult File(Stream fileStream, string contentType);
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual FileContentResult File(byte[] fileContents, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual FileContentResult File(byte[] fileContents, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, bool enableRangeProcessing);
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);
public virtual FileContentResult File(byte[] fileContents, string contentType, bool enableRangeProcessing);
public virtual FileContentResult File(byte[] fileContents, string contentType);
public virtual FileStreamResult File(Stream fileStream, string contentType, bool enableRangeProcessing);
public virtual ForbidResult Forbid(params string[] authenticationSchemes);
public virtual ForbidResult Forbid();
public virtual ForbidResult Forbid(AuthenticationProperties properties, params string[] authenticationSchemes);
public virtual ForbidResult Forbid(AuthenticationProperties properties);
public virtual LocalRedirectResult LocalRedirect(string localUrl);
public virtual LocalRedirectResult LocalRedirectPermanent(string localUrl);
public virtual LocalRedirectResult LocalRedirectPermanentPreserveMethod(string localUrl);
public virtual LocalRedirectResult LocalRedirectPreserveMethod(string localUrl);
public virtual NoContentResult NoContent();
public virtual NotFoundObjectResult NotFound([ActionResultObjectValue] object value);
public virtual NotFoundResult NotFound();
public virtual OkResult Ok();
public virtual OkObjectResult Ok([ActionResultObjectValue] object value);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName, bool enableRangeProcessing);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, bool enableRangeProcessing);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType);
public virtual ObjectResult Problem(string detail = null, string instance = null, int? statusCode = null, string title = null, string type = null);
public virtual RedirectResult Redirect(string url);
public virtual RedirectResult RedirectPermanent(string url);
public virtual RedirectResult RedirectPermanentPreserveMethod(string url);
public virtual RedirectResult RedirectPreserveMethod(string url);
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName, string fragment);
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName, object routeValues);
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName, object routeValues, string fragment);
public virtual RedirectToActionResult RedirectToAction(string actionName);
public virtual RedirectToActionResult RedirectToAction(string actionName, object routeValues);
public virtual RedirectToActionResult RedirectToAction();
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName, object routeValues, string fragment);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName, object routeValues);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName, string fragment);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, object routeValues);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName);
public virtual RedirectToActionResult RedirectToActionPermanentPreserveMethod(string actionName = null, string controllerName = null, object routeValues = null, string fragment = null);
public virtual RedirectToActionResult RedirectToActionPreserveMethod(string actionName = null, string controllerName = null, object routeValues = null, string fragment = null);
public virtual RedirectToPageResult RedirectToPage(string pageName);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, object routeValues, string fragment);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, string fragment);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, object routeValues);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler);
public virtual RedirectToPageResult RedirectToPage(string pageName, object routeValues);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, string pageHandler, string fragment);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, object routeValues);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, string pageHandler);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, string pageHandler, object routeValues, string fragment);
public virtual RedirectToPageResult RedirectToPagePermanentPreserveMethod(string pageName, string pageHandler = null, object routeValues = null, string fragment = null);
public virtual RedirectToPageResult RedirectToPagePreserveMethod(string pageName, string pageHandler = null, object routeValues = null, string fragment = null);
public virtual RedirectToRouteResult RedirectToRoute(string routeName);
public virtual RedirectToRouteResult RedirectToRoute(string routeName, object routeValues);
public virtual RedirectToRouteResult RedirectToRoute(string routeName, string fragment);
public virtual RedirectToRouteResult RedirectToRoute(string routeName, object routeValues, string fragment);
public virtual RedirectToRouteResult RedirectToRoute(object routeValues);
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, string fragment);
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, object routeValues);
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, object routeValues, string fragment);
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName);
public virtual RedirectToRouteResult RedirectToRoutePermanent(object routeValues);
public virtual RedirectToRouteResult RedirectToRoutePermanentPreserveMethod(string routeName = null, object routeValues = null, string fragment = null);
public virtual RedirectToRouteResult RedirectToRoutePreserveMethod(string routeName = null, object routeValues = null, string fragment = null);
public virtual SignInResult SignIn(ClaimsPrincipal principal, string authenticationScheme);
public virtual SignInResult SignIn(ClaimsPrincipal principal, AuthenticationProperties properties);
public virtual SignInResult SignIn(ClaimsPrincipal principal, AuthenticationProperties properties, string authenticationScheme);
public virtual SignInResult SignIn(ClaimsPrincipal principal);
public virtual SignOutResult SignOut();
public virtual SignOutResult SignOut(AuthenticationProperties properties);
public virtual SignOutResult SignOut(params string[] authenticationSchemes);
public virtual SignOutResult SignOut(AuthenticationProperties properties, params string[] authenticationSchemes);
public virtual StatusCodeResult StatusCode([ActionResultStatusCode] int statusCode);
Territus answered 21/9, 2021 at 10:34 Comment(0)
V
3

Thanks for your answers everybody. I went a slightly different route. I guess the point of that bit of code was that if the SendAsync fails in any sort of way, I want to return that error message. So instead, I changed it to be something like:

if (result.StatusCode != HttpStatusCode.OK)
{
    return BadRequest(result.ReasonPhrase);
}
Vesicate answered 2/8, 2018 at 12:46 Comment(1)
You should write an error handling middleware that will do it automatically for you.Flagging
A
3

This works for me. .NET Core 6.0

public async Task<IActionResult> GetAll(string catalogname,[FromQuery] GetAllQuery query)
    {
        String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";

        return Content(hardCodedJson , "application/json");
    }
Antietam answered 18/5, 2022 at 21:36 Comment(3)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Neilla
Thank you! So simple. I voted you up.None of the stuff people post here is ever easy or simple. Your solution is the new .NET CORE way. So of course works like a charm. PeaceMisconduct
If this helps others, his solution is superior to all others! It shows a typical IActionResult in ASP.NET Core. IActionResult return types allow you to return any type of data. In this case he has a "JSON string" that is formatted with escapes or slashes, typical in ASP.NET. The "return Content()" or ContentResult is an ActionResult type that allows you to return to the browser a Response including this string but with an HttpHeader Content-type (or mimetype) of "application/json". This tells the browser to accepts it as JSON. JSON is any valid JSON string, even with string formatting.Misconduct

© 2022 - 2024 — McMap. All rights reserved.