Friday 30 September 2016

ASP.NET Core 1.0 MVC Controller

Controller is heart of MVC. It is a glue between View and Model. It accepts request as input through Action Methods, while an action method may generate some response (for example list page and details page) or perform some task (for example add, update and delete). In simple, we can call Controller a group of related Action Methods with set of applicable rules. And it is responsible to manipulate data in form of Models and rendering of views as final result.

It is not required, but we have few conventions, which are followed throughout community but in actual they are not required. They are just followed as best practice.
  • A Controller has Controller Suffix. This convention is only followed to avoid name conflict and to make it easier to identify Controllers.

  • A Controller has to be in Controller Folder. We know that final output assembly have no concern of folder structure used in code. So this convention is solely in practice for code maintenance.
  • A Controller must inherent from Microsoft.AspNetCore.Mvc.Controller Class directly or indirectly. This practice is mainly used as Microsoft.AspNetCore.Mvc.Controller class provides us many methods also called Controller Helper methods and properties out of box. Controller helper methods are generally used to process and return response:
    • View
      • View helper method allows controller to specify view and model to be used.
      •  return View();  
         return View("ViewName");  
         return View(someObject);  
         return View("ViewName", someObject);  
    • Http Status Code
      • Http Status Code helper methods are a set of methods, which are used to return Http status code of specific type. Few important examples are as following:
        • BadRequest
        • NoContent
        • NotFound
        • Forbid
        • Unauthorized
      •  return BadRequest();  
         return Unauthorized();  
    • Formatted Response
      • Formatted Response helper methods allows the action method to return result in specific format. Few important examples are as following:
        • Json
        • Content
        • File
      •  return Json(someObject);  
         return Content(someObject);  
    • Content negotiated response
      • Content Negotiated Response helper methods allow to return a content negotiated response instead of custom object. Few important examples are as following:
        • Created
        • CreatedAtRoute 
        • CreatedAtAction
        • ChallengeResult
      •  return Created(uri, someObject);  
    • Redirect
      • Redirect helper methods allow to redirect the flow of request to some other action methods or route. Few important examples are as following:
        • Redirect
        • LocalRedirect
        • RedirectToAction
        • RedirectToRoute
      •  return RedirectToAction("ActionName");  
         return RedirectToAction("ActionName", someObject);   
         return RedirectToAction("ControllerName", "ActionName", someObject);
    • Any Object or Type
      • If an action method just returns an object or a collection of objects then returned data is formatted based on request parameters. For ASP.NET Core Json is default option. 
        • Native Types (int, string)
        • Complex Type (any class or generics)
      •  return "Hello Controllers";  
         return someObject;  return ListOfObjects;

Action Method

Action Method is unit of Controller. It is any public method and may have parameter of native or complex type, for example, Index or List Action Method may not have any parameter, Get Action Method may have a parameter as Id and a Update or Create Action Method may have complex ViewModel as parameter. Action Method parameters are populated using Model Binding, please refer to ASP.NET Core 1.0 MVC Model for more details on Model Binding. It is not rough and tough rule, but in general, an action methods perform following set of tasks:
  • Process request parameters and map them to data provider components. We may also consider InputFormatter and Parameter Mapping in this area. It may also involve input Data Validation. For more details on Model Binding and Parameter Mapping, please refer to ASP.NET Core 1.0 MVC Model. We will discuss InputFormatter and Data Validation in detail in future sessions.
  • These data provider components can be any repository, any data service or any business logic component. For .NET Core it is recommended to use data provider components as services, and these services are generally made available to Controller using Dependency Injection. We will discuss Dependency Injection in detail in future sessions.
  • Process response data and map them to final response output. Depending upon type of application, action method selects the response type. In normal MVC application, we mostly cater with IActionResult. We may return view. Please refer to ASP.NET Core 1.0 MVC View for more details about Views.

Additional Features

There are many other features related with controllers like following, but we may discuss them in different sessions in future:
  • Filters
  • Exception Handling
  • Response Cache
  • Routing
  • Controller Scaffolding
  • Web API
  • Authentication and Authorization
  • Dependency Injection
  • Testing

Further Reading

For further details, please refer to official documentation at:

No comments:

Post a Comment