ASP.NET MVC Core Controller Action Method and Types of Action Result

This blog explains what is MVC Controller, Action Method, and different types of ActionResult like HTML returning, Content, Redirect, File, Status Code, Security related.

What is ASP.NET MVC Core Controller

The controller is an MVC component responsible to handle user actions, work with required models for business rule processing and render a specific view. Controller classes are by default added to the project's Controllers folder. If you are having MVC Area, then you will have a Controller under Area to provide a logical grouping of similar actions. Controller classes are inherited from Microsoft.AspNetCore.MVC.Controller.

The controller is the initial entry point of any MVC application and its Request life cycle and controls each user request by routing to the correct Action method.

ASP.NET MVC Core Action Methods

Every public method of the controller is ActionMethod except methods marked as [NonAction]. Action methods are similar to normal methods however ActionMethod has limitations as

  • Action method must be public, it can not be private.
  • Action method can not be static or extension method.
  • Action method can not be getter or setter.
  • Action method should not be part of Microsoft.AspNetCore.Mvc.Controller.
  • Action method can not contain ref or out parameters.

ActionMethod Overloading

ActionMethod accepts primitive or complex parameters. Method overloading can be used with ActionName by using the [ActionName] attribute or by using different HTTP verbs. The following code is valid even though it has the same ActionMethod name.


public class ProductController : Controller  
{  
    [ActionName("GetProductNameByID")]  
    public string GetProductName(int ProductID)  
    {  
        return "Product name is ABC.";  
    }  

    [ActionName("GetProductNameByProductCode")]
    public string GetProductName(string code)  
    {  
        return "Product name is ABC.";  
    }  

    [HttpGet]
    public ActionResult ProdutDetails(int ProductID)  
    {  
        --code to get details of product from data store
        return View();  
    }

    [HttpPost]  
    public ActionResult ProdutDetails(Product product)  
    {  
        --post (add or update) product details in data store.
        return View(product);  
    }
}

The following code will throw an error as there is no [ActionName] defined and method names are same.


public class ProductController : Controller  
{    
    public string GetProductName(int ProductID)  
    {  
        return "Product name is ABC.";  
    }

    public string GetProductName(string code)  
    {  
        "Product name is ABC.";  
    }
}

The values of ActionMethod parameters are retrieved from the requests data collection. ASP.NET MVC Core Model Binding bind requests data collection and ActionMethod parameters automatically if their name matches with each other.

Routing is the process using which the MVC application matches the incoming request and executes the corresponding ActionMethod. ASP.NET MVC Core uses middleware to map requests and action methods.

Action Result

The controller Action Method returns Action Results to the client as a response. This Action Result can be a simple string, int or complex types like JSON, HTML Views or File to Download, etc. All types of ActionResult classes are inherited from the ActionResult abstract class and the IActionResult interface. Both abstract class and interface are defined in Microsoft.AspNetCore.Mvc interface.

Action Result Set

All action results can be classified in below set depending on what type of result set it is returning.

  1. Content Resulting HTML

    ViewResult

    These action results returns HTML response. In the form of ViewResult or PartialViewResult. The View() method returns HTML to client. This ActionResult prepares HTML markup with some static values or inject model data. By default View() returns a view having the same name as ActionMethod being executed.

    For example your application is executing a ActionMethod from Application -> Area -> Employee -> Controllers -> EmployeeController -> Index then by default it will render a .cshtml view located at Application -> Area -> Employee -> Views -> Employee -> index.cshtml.

    Following code invokes Index ActionMethod that binds a model and returns ViewResult.

    public IActionResult Index()
    {
        EmployeeModel employee = new EmployeeModel()
        {
            EmployeeID = 1,
            FirstName = "Paul",
            LastName = "Andrew",
            Location = "Mumbai",
            Email = "Paul@geeksarray.com"
        };
        return View(employee);
    }
    

    This generates output as

    ASP.NET MVC Core ViewResult with model

    PartialViewResult

    Partial View returns part of the main view. It is a reusable component for multiple views and can be used in multiple views or layout view. PartialViewResult class is inherited from ActionResult base class and IActionResult, IStatusCodeActionResult interface. IStatusCodeActionResult produce HTTP response with HTTP Status Code.

    By convention partial view name has prefix _ and add each partial view to the Shared folder. There are multiple ways to render PartialView.

    Following code renders partail view address through HTML of main view Employee. This address partial view can be used for employee address, customer address, or billing address. Employee View passes Address model to partial view.

    <div>
        @{ @await Html.PartialAsync("_address", Model.EmployeeAddress);}
    </div>
                    
    
  2. Content Result

    The content result produces some kind of content for client. The content can be anything like HTML, JSON, text, XML string.

    Content result can return JsonResult, ContentResult, EmptyResult. For more details on ContentResult visit - ASP.NET Core MVC ContentResult.

    The content result has three properties

    1. Content: Gets or sets the content of the response body. The content can be a formatted value of JSON string, plain text, or XML string.
    2. ContentType: Gets or sets Content-type header of response. It is a string property and it can have a value of valid MIME type like text/plain, text/html
    3. StatusCode: Gets or sets HTTP Status Code.

    The following code returns HTML string with bold text.

    public ContentResult ContentResultTest()
    {
        return Content("Hello from GeeksArray", "text/html", System.Text.Encoding.UTF8);
    }
    

    This generates following output.

    ASP.NET Core MVC ContentResult

  3. Redirect Results

    The redirect results redirect clients to the new location. Redirect can be permanent or temporary. Also, this redirection can be with absolute or relative URL from the current request's action method.

    Redirection with redirect results returns HTTP Status code 302 Found (Temporarily moved), 301 Moved Permanently, 308 Permanent Redirect, 307 Temporary Redirect.

    All following return statements redirect the client to the Index action method of the Product Controller with some difference in execution. Redirect result has return types RedirectResult, LocalRedirectResult, RedirectToActionResult, RedirectToRouteResult. For more details on each RedirectResult see - How to redirect ASP.NET Core MVC request.

    return Redirect("/Product/Index");
    return RedirectPermanent("/Product/Index");
    return RedirectPermanentPreserveMethod("/Product/Index");
    return RedirectPreserveMethod("/Product/Index"); 
    

    The following diagram shows the redirection result from one URL to another. This method redirects to the new URL by returning HTTP status code 308( Permanent Redirect ) Also this redirection preserves current HTTP request type (GET / POST).

    ASP.NET Core MVC RedirectResult

  4. File Results

    The file result returns a file to use that can be rendered on the client browser. File results write files as response. FileResult is an abstract base class that sends binary content to the response.

    FileResult can use FileResult, FileContentResult, VirtualFileResult, PhysicalFileResult to return files to browser. Each file result type has a different way of execution. For more detailed description of each file result type visit - ASP.NET Core MVC FileResult.

    Following code renders pdf-sample.pdf file located under wwwroot -> downloads folder.

    public FileResult FileResultTest()
    {
        return File("~/downloads/pdf-sample.pdf", "application/pdf");
    }
               
  5. Status Code Results

    Status code results return errors and HTTP codes to the client. These Action Results are majorly used in Web API controllers.

    Status Code result can be any of the action result from StatusCodeResult, ObjectResult, OkResult, OkObjectResult, CreatedResult, CreatedAtActionResult, CreatedAtRouteResult, BadRequestResult, BadRequestObjectResult, NotFoundResult, NotFoundObjectResult, UnsupportedMediaTypeResult, NoContentResult,

    The following code returns HTTP Status code 200 (OK) to the client.

    public StatusCodeResult StatusCodeResultTest()
    {
        return StatusCode(200);            
    }
    
  6. Security Related Results

    These results hold authentication and authorization properties and return authentication and authorization operation results to the client.

    This includes action results like SignInResult, SignOutResult, ForbidResult, ChallengeResult, UnauthorizedResult.

    The following result set can be returned to the client if the user is not authorized to execute a specific action method.

    return new UnauthorizedResult();
    

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!