Skip to main content

ASP.NET Core - Action Results

We will discuss the Action Results.
  • This base class gives us access to lots of contextual information about a request, as well as methods that help us build results to send back to the client.
  • You can send back simple strings and integers in a response. You can also send back complex objects like an object to represent a student or university or restaurant etc. and all the data associated with that object.
  • These results are typically encapsulated into an object that implements the IActionResult interface.
  • There are many different result types that implement this interface — result types that can contain models or the contents of a file for download.
  • These different result types can allow us to send back JSON to a client or XML or a view that builds HTML.
Actions basically return different types of Action Results. The ActionResult class is the base for all the action results. The following is a list of different kind of action results and their behavior.
NameBehavior
ContentResultReturns a string
FileContentResultReturns file content
FilePathResultReturns file content
FileStreamResultReturns file content.
EmptyResultReturns nothing
JavaScriptResultReturns script for execution
JsonResultReturns JSON formatted data
RedirectToResultRedirects to the specified URL
HttpUnauthorizedResultReturns 403 HTTP Status code
RedirectToRouteResultRedirect to different action/ different controller action
ViewResultReceived as a response for view engine
PartialViewResultReceived as a response for view engine

Example 1

Let us perform a simple example by opening the HomeController class and derive it from the controller based class. This base class is in the Microsoft.AspNet.Mvc namespace. The following is the implementation of the HomeController class.
using Microsoft.AspNet.Mvc; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;  

namespace FirstAppdemo.Controllers  { 
   public class HomeController : Controller { 
      public ContentResult Index() { 
         return Content("Hello, World! this message is from 
            Home Controller using the Action Result"); 
      } 
   } 
}
You can now see that the index method is returning the ContentResult which is one of the result types and all these result types implement ultimately an interface, which is the ActionResult.
In the Index method, we have passed a string into the Content method. This Content method produces a ContentResult; this means the Index method will now return ContentResult.
Let us save the HomeController class and run the application in the browser. It will produce the following page.
Action Result
You can now see a response which doesn’t look any different from the response we had before. It is still just going to be a plain text response.
  • You might be wondering what is the advantage of using something that produces an ActionResult.
  • The typical advantage is that it is just a formal way to encapsulate the decision of the controller.
  • The controller decides what to do next, either return a string or HTML or return a model object that might be serialized into JSON etc.
  • All that the controller needs to do is make that decision and the controller does not have to write directly into the response the results of its decision.
  • It just needs to return the decision and then it is the framework that will take a result and understand how to transform that result into something that can be sent back over HTTP.

Example 2

Let us take another example. Create a new folder in the project and call it Models. Inside the Models folder, we want to add a class that can represent an Employee.
Models
Enter Employee.cs in the Name field as in the above screenshot. Here, the implementation of the Employee class contains two properties.
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;  

namespace FirstAppDemo.Models { 
   public class Employee { 
      public int ID { get; set; } 
      public string Name { get; set} 
   } 
}
Inside the Index action method of HomeController, we want to return an Employee object. The following is the implementation of HomeController.
using FirstAppDemo.Models; 
using Microsoft.AspNet.Mvc; 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;  

namespace FirstAppdemo.Controllers { 
   public class HomeController : Controller { 
      public ObjectResult Index() { 
         var employee = new Employee { ID = 1, Name = "Mark Upston"}; 
         return new ObjectResult(employee); 
      } 
   } 
} 
Now, instead of returning the Content, we will return a different type of result which is known as ObjectResult. If we want an ObjectResult, we need to create or instantiate an ObjectResult and pass into it some model object.
  • An ObjectResult is special in the MVC framework because when we return an ObjectResult, the MVC framework looks at this object. This object needs to be represented in the HTTP response.
  • This object should be serialized into XML or JSON or some other format and ultimately, the decision will be made based on the configuration information that you give to the MVC at startup. If you don't configure anything, you just get some defaults, and the default is a JSON response.
Save all your files and refresh the browser. You will see the following output.
Mark Upston

Comments

Popular posts from this blog

ASP.NET Core - Create New Project

You can start building a new ASP.NET Core Application from the  File → New Project  menu option. On the New Project dialog box, you will see the following three different templates for Web projects − ASP.NET Web Application  − The simple ASP.NET application templates . ASP.NET Core Web Application (.NET Core)  − This will start you with a crossplatform compatible project that runs on the .NET Core framework. ASP.NET Core Web Application (.NET Framework)  − This starts a new project that runs on the standard .NET Framework on Windows. In the left pane, select  Templates → Visual C# → Web  and in the middle pane select the ASP.NET Core Web Application (.NET Core) template. Let us call this application  FirstAppDemo  and also specify the Location for your ASP.NET Core project and then Click OK. In the above dialog box, you can select a specific template for the ASP.NET application from the available ASP.NET Core Templates. ...

ASP.NET Core - Attribute Routes

Learn another approach to routing and that is attribute-based routing. With attribute-based routing, we can use C# attributes on our controller classes and on the methods internally in these classes. These attributes have metadata that tell ASP.NET Core when to call a specific controller. It is an alternative to convention-based routing. Routes are evaluated in the order that they appear, the order that you register them in, but it's quite common to map multiple routes particularly if you want to have different parameters in the URL or if you want to have different literals in the URL. Example Let us take a simple example. Open the  FirstAppDemo  project and run the application in the browser. When you specify  /about , it will produce the following output − What we want here is that when we specify  /about , the application should invoke the Phone action of the AboutController. Here, we can enforce some explicit routes for this controller using a Ro...

Features of Node.js

Following are some of the important features that make Node.js the first choice of software architects. Asynchronous and Event Driven  − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Very Fast  − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable  − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than t...