skip to Main Content

I am trying to understand what the pros and cons are of IActionResult and IResult as return types and when to use the approopriate one. From what i’ve gathered IActionResult is just like IResult but with more options on how to handle the result?

2

Answers


  1. IActionResult :: Defines a contract that represents the result of an action method.ASP.NET Core 7

    IActionResult allows you to provide some more operations based on your actions like redirecting, changing the response’s format etc.

    Use IActionResult on the side of your web application – MVC, since it gives you more approaches to handle requests.

    IResult :: Defines a contract that represents the result of an HTTP endpoint. ASP.NET Core 7

    ASP.NET Core is a new static Results utility class to produce common HTTP responses as IResults. IResult is a new return type that got introduced with Minimal APIs.

    Login or Signup to reply.
  2. IActionResult: Defines a contract that represents the result of an action method.

    Example:

    public IActionResult OkResult()
    {
        return Ok();
    }
    

    or

    public IActionResult NoContentResult()
    {
        return NoContent();
    }
    

    IResult: Defines a contract that represents the result of an HTTP endpoint.

    Example:

    class CusomtHTMLResult : IResult
    {
        private readonly string _htmlContent;
        public CusomtHTMLResult(string htmlContent)
        {
            _htmlContent = htmlContent;
        }
        public async Task ExecuteAsync(HttpContext httpContext)
        {
            httpContext.Response.ContentType = MediaTypeNames.Text.Html;
            httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(_htmlContent);
            await httpContext.Response.WriteAsync(_htmlContent);
        }
    }
    
    • (Line: 1) The ‘CustomHTMLResult’ implementing the
      ‘Microsoft.AspNetCore.Http.IResult’.

    • (Line: 3-7) Injecting the HTML result.

    • (Line: 8) The ‘ExecuteAsync’ method gets automatically executed on
      initializing ‘CustomHTMLResult’ object.

    • (Line: 10-12) Updating the ‘HttpContext’ object with our HTML
      response, like defining ‘ContentType’, ‘ContentLength’.

       static class CustomResultExtensions
       {
       public static IResult HtmlResponse(this IResultExtensions extensions, string html)
       {
           return new CusomtHTMLResult(html);
       }
      

      }

    • The ‘CustomResultExtions’ is a static class. where we can define the extension method of our custom response.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search