Advantage of using IActionResult as result type in ActionsWhat is the difference between returning a model vs ActionResult<Model> in an API controller?How to write custom actionResult in asp.net coreasync Task<IActionResult> vs Task<T>What should be returned from the Get request in the web API?@Html.EditorFor doesn't return specific types to the controllerMVC 6 - ViewModel Builder ConceptHandle IActionResult in MVC6Why won't my ASP.Net Core Web API Controller return XML?How to return a custom HTTP status/message in ASP.NET Core without returning object, IActionResult, etc?Unit testing controller methods which return IActionResultHow to return a StatusCode object outside of an MVC ControllerHow can I call a controller action when rendering a partial view?.Net Core WebAPI connection reset, when I have “include” in my controllersimple controller index action says “value”

How could indestructible materials be used in power generation?

Method Does Not Exist error message

What is the idiomatic way to say "clothing fits"?

Why does this cyclic subgroup have only 4 subgroups?

What mechanic is there to disable a threat instead of killing it?

Detention in 1997

What type of content (depth/breadth) is expected for a short presentation for Asst Professor interview in the UK?

Apex Framework / library for consuming REST services

In 'Revenger,' what does 'cove' come from?

Determining Impedance With An Antenna Analyzer

Avoiding the "not like other girls" trope?

Am I breaking OOP practice with this architecture?

How badly should I try to prevent a user from XSSing themselves?

How can I deal with my CEO asking me to hire someone with a higher salary than me, a co-founder?

Arrow those variables!

Do scales need to be in alphabetical order?

Plagiarism or not?

Bullying boss launched a smear campaign and made me unemployable

What does “the session was packed” mean in this context?

How much of data wrangling is a data scientist's job?

Cursor Replacement for Newbies

Short story with a alien planet, government officials must wear exploding medallions

How do conventional missiles fly?

How would I stat a creature to be immune to everything but the Magic Missile spell? (just for fun)



Advantage of using IActionResult as result type in Actions


What is the difference between returning a model vs ActionResult<Model> in an API controller?How to write custom actionResult in asp.net coreasync Task<IActionResult> vs Task<T>What should be returned from the Get request in the web API?@Html.EditorFor doesn't return specific types to the controllerMVC 6 - ViewModel Builder ConceptHandle IActionResult in MVC6Why won't my ASP.Net Core Web API Controller return XML?How to return a custom HTTP status/message in ASP.NET Core without returning object, IActionResult, etc?Unit testing controller methods which return IActionResultHow to return a StatusCode object outside of an MVC ControllerHow can I call a controller action when rendering a partial view?.Net Core WebAPI connection reset, when I have “include” in my controllersimple controller index action says “value”













19















What's the advantage or recommendation on using IActionResult as the return type of a WebApi controller instead of the actual type you want to return?



Most of the examples I've seen return IActionResult, but when I build my first site I exclusively use View Model classes as my return types.... now I feel like I did it all wrong!










share|improve this question




























    19















    What's the advantage or recommendation on using IActionResult as the return type of a WebApi controller instead of the actual type you want to return?



    Most of the examples I've seen return IActionResult, but when I build my first site I exclusively use View Model classes as my return types.... now I feel like I did it all wrong!










    share|improve this question


























      19












      19








      19


      3






      What's the advantage or recommendation on using IActionResult as the return type of a WebApi controller instead of the actual type you want to return?



      Most of the examples I've seen return IActionResult, but when I build my first site I exclusively use View Model classes as my return types.... now I feel like I did it all wrong!










      share|improve this question
















      What's the advantage or recommendation on using IActionResult as the return type of a WebApi controller instead of the actual type you want to return?



      Most of the examples I've seen return IActionResult, but when I build my first site I exclusively use View Model classes as my return types.... now I feel like I did it all wrong!







      asp.net-core asp.net-core-mvc






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 23 '16 at 18:09









      Tseng

      35.4k595127




      35.4k595127










      asked Jun 23 '16 at 17:34









      Zeus82Zeus82

      2,08932554




      2,08932554






















          2 Answers
          2






          active

          oldest

          votes


















          16














          The main advantage is that you can return error/status codes or redirects/resource urls.



          For example:



          public IActionResult Get(integer id) 

          var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();

          if(user == null)

          // Returns HttpCode 404
          return NotFound();


          // returns HttpCode 200
          return ObjectOk(user);



          or



          public IActionResult Create(User user) 

          if(!ModelState.IsValid)

          // returns HttpCode 400
          return BadRequest(ModelState);


          db.Users.Add(user);
          db.SaveChanges();

          // returns HttpCode 201
          return CreatedAtActionResult("User", "Get", new id = user.Id );






          share|improve this answer

























          • Also unit testing

            – Kiran Challa
            Jun 23 '16 at 20:08











          • @KiranChalla I don't understand what we get with IActionResult which we can't get with ActionResult, is ActionResult limit us in some way? The other answers on the internet is not that compelling.

            – Hamid Mosalla
            Mar 25 '17 at 18:34






          • 2





            @HamidMosalla; Technically not much, but IActionResult is an interface and ActionResult an abstract class. While all ActionResults from MVC inherit from ActionResult, it is not given or guaranteed, that some 3rd party action result classes do the same, so it's always best to use the lowest possible type, here: IActionResult

            – Tseng
            Mar 25 '17 at 20:24











          • @Tseng I know IActionResult' is an interface and doesn't have the synchronous version of ExecuteResult` method as opposed to ActionResult, I didn't find anything different from a consumer perspective, I think it might be a more of a framework design decision in which we consumer of that framework should not care about that much.

            – Hamid Mosalla
            Mar 26 '17 at 2:21











          • @Tseng I am late to the party, but you can also return BadRequest and CreatedAtActionResult with IActionResult, which makes it seem like there are no advantages with IActionResult then according to your examples.

            – thesystem
            Dec 22 '18 at 16:41


















          1














          The main advantage is that you can easily test your code using a mocking framework.



          And as you build your controllers, you can easily change your return object as well. IActionResult is a interface and has many implementations like JsonResult, ViewResult, FileResult and so on.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37998291%2fadvantage-of-using-iactionresult-as-result-type-in-actions%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            16














            The main advantage is that you can return error/status codes or redirects/resource urls.



            For example:



            public IActionResult Get(integer id) 

            var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();

            if(user == null)

            // Returns HttpCode 404
            return NotFound();


            // returns HttpCode 200
            return ObjectOk(user);



            or



            public IActionResult Create(User user) 

            if(!ModelState.IsValid)

            // returns HttpCode 400
            return BadRequest(ModelState);


            db.Users.Add(user);
            db.SaveChanges();

            // returns HttpCode 201
            return CreatedAtActionResult("User", "Get", new id = user.Id );






            share|improve this answer

























            • Also unit testing

              – Kiran Challa
              Jun 23 '16 at 20:08











            • @KiranChalla I don't understand what we get with IActionResult which we can't get with ActionResult, is ActionResult limit us in some way? The other answers on the internet is not that compelling.

              – Hamid Mosalla
              Mar 25 '17 at 18:34






            • 2





              @HamidMosalla; Technically not much, but IActionResult is an interface and ActionResult an abstract class. While all ActionResults from MVC inherit from ActionResult, it is not given or guaranteed, that some 3rd party action result classes do the same, so it's always best to use the lowest possible type, here: IActionResult

              – Tseng
              Mar 25 '17 at 20:24











            • @Tseng I know IActionResult' is an interface and doesn't have the synchronous version of ExecuteResult` method as opposed to ActionResult, I didn't find anything different from a consumer perspective, I think it might be a more of a framework design decision in which we consumer of that framework should not care about that much.

              – Hamid Mosalla
              Mar 26 '17 at 2:21











            • @Tseng I am late to the party, but you can also return BadRequest and CreatedAtActionResult with IActionResult, which makes it seem like there are no advantages with IActionResult then according to your examples.

              – thesystem
              Dec 22 '18 at 16:41















            16














            The main advantage is that you can return error/status codes or redirects/resource urls.



            For example:



            public IActionResult Get(integer id) 

            var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();

            if(user == null)

            // Returns HttpCode 404
            return NotFound();


            // returns HttpCode 200
            return ObjectOk(user);



            or



            public IActionResult Create(User user) 

            if(!ModelState.IsValid)

            // returns HttpCode 400
            return BadRequest(ModelState);


            db.Users.Add(user);
            db.SaveChanges();

            // returns HttpCode 201
            return CreatedAtActionResult("User", "Get", new id = user.Id );






            share|improve this answer

























            • Also unit testing

              – Kiran Challa
              Jun 23 '16 at 20:08











            • @KiranChalla I don't understand what we get with IActionResult which we can't get with ActionResult, is ActionResult limit us in some way? The other answers on the internet is not that compelling.

              – Hamid Mosalla
              Mar 25 '17 at 18:34






            • 2





              @HamidMosalla; Technically not much, but IActionResult is an interface and ActionResult an abstract class. While all ActionResults from MVC inherit from ActionResult, it is not given or guaranteed, that some 3rd party action result classes do the same, so it's always best to use the lowest possible type, here: IActionResult

              – Tseng
              Mar 25 '17 at 20:24











            • @Tseng I know IActionResult' is an interface and doesn't have the synchronous version of ExecuteResult` method as opposed to ActionResult, I didn't find anything different from a consumer perspective, I think it might be a more of a framework design decision in which we consumer of that framework should not care about that much.

              – Hamid Mosalla
              Mar 26 '17 at 2:21











            • @Tseng I am late to the party, but you can also return BadRequest and CreatedAtActionResult with IActionResult, which makes it seem like there are no advantages with IActionResult then according to your examples.

              – thesystem
              Dec 22 '18 at 16:41













            16












            16








            16







            The main advantage is that you can return error/status codes or redirects/resource urls.



            For example:



            public IActionResult Get(integer id) 

            var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();

            if(user == null)

            // Returns HttpCode 404
            return NotFound();


            // returns HttpCode 200
            return ObjectOk(user);



            or



            public IActionResult Create(User user) 

            if(!ModelState.IsValid)

            // returns HttpCode 400
            return BadRequest(ModelState);


            db.Users.Add(user);
            db.SaveChanges();

            // returns HttpCode 201
            return CreatedAtActionResult("User", "Get", new id = user.Id );






            share|improve this answer















            The main advantage is that you can return error/status codes or redirects/resource urls.



            For example:



            public IActionResult Get(integer id) 

            var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();

            if(user == null)

            // Returns HttpCode 404
            return NotFound();


            // returns HttpCode 200
            return ObjectOk(user);



            or



            public IActionResult Create(User user) 

            if(!ModelState.IsValid)

            // returns HttpCode 400
            return BadRequest(ModelState);


            db.Users.Add(user);
            db.SaveChanges();

            // returns HttpCode 201
            return CreatedAtActionResult("User", "Get", new id = user.Id );







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jun 27 '16 at 6:40

























            answered Jun 23 '16 at 18:06









            TsengTseng

            35.4k595127




            35.4k595127












            • Also unit testing

              – Kiran Challa
              Jun 23 '16 at 20:08











            • @KiranChalla I don't understand what we get with IActionResult which we can't get with ActionResult, is ActionResult limit us in some way? The other answers on the internet is not that compelling.

              – Hamid Mosalla
              Mar 25 '17 at 18:34






            • 2





              @HamidMosalla; Technically not much, but IActionResult is an interface and ActionResult an abstract class. While all ActionResults from MVC inherit from ActionResult, it is not given or guaranteed, that some 3rd party action result classes do the same, so it's always best to use the lowest possible type, here: IActionResult

              – Tseng
              Mar 25 '17 at 20:24











            • @Tseng I know IActionResult' is an interface and doesn't have the synchronous version of ExecuteResult` method as opposed to ActionResult, I didn't find anything different from a consumer perspective, I think it might be a more of a framework design decision in which we consumer of that framework should not care about that much.

              – Hamid Mosalla
              Mar 26 '17 at 2:21











            • @Tseng I am late to the party, but you can also return BadRequest and CreatedAtActionResult with IActionResult, which makes it seem like there are no advantages with IActionResult then according to your examples.

              – thesystem
              Dec 22 '18 at 16:41

















            • Also unit testing

              – Kiran Challa
              Jun 23 '16 at 20:08











            • @KiranChalla I don't understand what we get with IActionResult which we can't get with ActionResult, is ActionResult limit us in some way? The other answers on the internet is not that compelling.

              – Hamid Mosalla
              Mar 25 '17 at 18:34






            • 2





              @HamidMosalla; Technically not much, but IActionResult is an interface and ActionResult an abstract class. While all ActionResults from MVC inherit from ActionResult, it is not given or guaranteed, that some 3rd party action result classes do the same, so it's always best to use the lowest possible type, here: IActionResult

              – Tseng
              Mar 25 '17 at 20:24











            • @Tseng I know IActionResult' is an interface and doesn't have the synchronous version of ExecuteResult` method as opposed to ActionResult, I didn't find anything different from a consumer perspective, I think it might be a more of a framework design decision in which we consumer of that framework should not care about that much.

              – Hamid Mosalla
              Mar 26 '17 at 2:21











            • @Tseng I am late to the party, but you can also return BadRequest and CreatedAtActionResult with IActionResult, which makes it seem like there are no advantages with IActionResult then according to your examples.

              – thesystem
              Dec 22 '18 at 16:41
















            Also unit testing

            – Kiran Challa
            Jun 23 '16 at 20:08





            Also unit testing

            – Kiran Challa
            Jun 23 '16 at 20:08













            @KiranChalla I don't understand what we get with IActionResult which we can't get with ActionResult, is ActionResult limit us in some way? The other answers on the internet is not that compelling.

            – Hamid Mosalla
            Mar 25 '17 at 18:34





            @KiranChalla I don't understand what we get with IActionResult which we can't get with ActionResult, is ActionResult limit us in some way? The other answers on the internet is not that compelling.

            – Hamid Mosalla
            Mar 25 '17 at 18:34




            2




            2





            @HamidMosalla; Technically not much, but IActionResult is an interface and ActionResult an abstract class. While all ActionResults from MVC inherit from ActionResult, it is not given or guaranteed, that some 3rd party action result classes do the same, so it's always best to use the lowest possible type, here: IActionResult

            – Tseng
            Mar 25 '17 at 20:24





            @HamidMosalla; Technically not much, but IActionResult is an interface and ActionResult an abstract class. While all ActionResults from MVC inherit from ActionResult, it is not given or guaranteed, that some 3rd party action result classes do the same, so it's always best to use the lowest possible type, here: IActionResult

            – Tseng
            Mar 25 '17 at 20:24













            @Tseng I know IActionResult' is an interface and doesn't have the synchronous version of ExecuteResult` method as opposed to ActionResult, I didn't find anything different from a consumer perspective, I think it might be a more of a framework design decision in which we consumer of that framework should not care about that much.

            – Hamid Mosalla
            Mar 26 '17 at 2:21





            @Tseng I know IActionResult' is an interface and doesn't have the synchronous version of ExecuteResult` method as opposed to ActionResult, I didn't find anything different from a consumer perspective, I think it might be a more of a framework design decision in which we consumer of that framework should not care about that much.

            – Hamid Mosalla
            Mar 26 '17 at 2:21













            @Tseng I am late to the party, but you can also return BadRequest and CreatedAtActionResult with IActionResult, which makes it seem like there are no advantages with IActionResult then according to your examples.

            – thesystem
            Dec 22 '18 at 16:41





            @Tseng I am late to the party, but you can also return BadRequest and CreatedAtActionResult with IActionResult, which makes it seem like there are no advantages with IActionResult then according to your examples.

            – thesystem
            Dec 22 '18 at 16:41













            1














            The main advantage is that you can easily test your code using a mocking framework.



            And as you build your controllers, you can easily change your return object as well. IActionResult is a interface and has many implementations like JsonResult, ViewResult, FileResult and so on.






            share|improve this answer



























              1














              The main advantage is that you can easily test your code using a mocking framework.



              And as you build your controllers, you can easily change your return object as well. IActionResult is a interface and has many implementations like JsonResult, ViewResult, FileResult and so on.






              share|improve this answer

























                1












                1








                1







                The main advantage is that you can easily test your code using a mocking framework.



                And as you build your controllers, you can easily change your return object as well. IActionResult is a interface and has many implementations like JsonResult, ViewResult, FileResult and so on.






                share|improve this answer













                The main advantage is that you can easily test your code using a mocking framework.



                And as you build your controllers, you can easily change your return object as well. IActionResult is a interface and has many implementations like JsonResult, ViewResult, FileResult and so on.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jun 23 '16 at 18:21









                gnllucenagnllucena

                60966




                60966



























                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37998291%2fadvantage-of-using-iactionresult-as-result-type-in-actions%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to get text form Clipboard with JavaScript in Firefox 56?How to validate an email address in JavaScript?How do JavaScript closures work?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I copy to the clipboard in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                    List of MPs elected to the English parliament in 1640 (April) Contents List of constituencies and members See also Notes References Navigation menueNational Archives – The Glynde Place ArchivesCobbett's Parliamentary history of England, from the Norman Conquest in 1066 to the year 1803'Aldermen in Parliament', The Aldermen of the City of London: Temp. Henry III – 1912onepage&q&f&#61, false 229