Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 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
–
–
–
–
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);
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);
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");
–
–
–
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.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.