Download presentation
Presentation is loading. Please wait.
Published byJuliet Walsh Modified over 5 years ago
1
Chengyu Sun California State University, Los Angeles
CS4540 Special Topics in Web Development ASP.NET Core: Handling Requests with Controllers Chengyu Sun California State University, Los Angeles
2
Controllers in ASP.NET Core MVC
Any class that meets at least one of the two conditions: Have a name ending in Controller Inherit from ControllerBase or Controller class Usually placed in the Controllers folder but can be anywhere in the project
3
A Controller Example public class EmployeesController : Controller {
public IActionResult List() var employees = employeeService.GetEmployees(); return View( employees ); }
4
What Does An Action Method Return?
An action method can return a view (or part of a view), which renders a response (or part of a response) An action method can also return a response, which can be a redirect, error, file, JSON, and so on IActionResult is the interface for all the possible return values of an action method
5
A Quick Look at the ControllerBase Class
The base class for Controller Properties for accessing various data related to a request Helper methods for creating various responses, e.g. Ok, NotFound, File, Redirect Usually used as the base class for web API controllers
6
A Quick Look at the Controller Class
Inherits from ControllerBase Adds support for views Type Name Usage Property ViewBag, ViewData For passing additional data to views TempData Single-use session data (usually used for redirect) Method View, PartialView, ViewComponent, Json For creating ViewResult or JsonResult OnActionExecuted, OnActionExecuting, OnActionExecutionAsync, Dispose Controller life cycle hooks
7
ViewData ViewData is a Dictionary<string,object> In controller:
ViewData["employees"] = employees; Require casting In view: @foreach (var employee in (List<Employee>) ViewData["employees"]) { <tr> </tr> }
8
ViewBag ViewBag is an ExpandoObject (i.e. expandable object)
Supports dynamic properties whose types are determined at runtime, i.e. no casting necessary A wrapper of ViewData Example: ViewBag.employees = employees;
9
View Model vs. ViewData vs. ViewBag
Type declared in view Type can be determined at compilation time, thus allows code suggestion/completion in IDEs ViewData Dictionary<string,object> Require casting from object to the real type of the data ViewBag ExpandoObject Property types are determined at runtime – no casting required Why do we have ViewData when ViewBag seems better??
10
Example: View an Employee
Route: "{controller=Home}/{action=Index}/{id?}" URL: Employees / View / 1 EmployeesController: IActionResult View( int id )
11
Routing in ASP.NET Core Map URLs of requests to controller actions
Conventional routing is based on routes specified for the MVC middleware (i.e. each route establishes a convention) Attribute routing specifies mapping on a controller or action method, e.g. [Route("Employees/List")] public IActionResult List() { … }
12
A Route in Conventional Routing
routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); A route in conventional routing must have a controller and an action
13
Route Template Route parameters
"{controller=Home} / {action=Index} / {id?}" No leading / Route parameters must be separated by literal values controller and action are reserved names Default value and optional parameter
14
Example: View Two Employees
Use URL like /Employees/Two/1/2 Use URL like /Employees/Two/1-2 Routes order is important – router will try each route in order and stop at the first match
15
Example: Wiki URLs Use a catch-all route parameter, e.g. "wiki/{*path}" or "wiki/{**path}" There's no difference between * and ** when using the parameter in an action method
16
Attribute Routing Examples
[Route("Home/About")] public IActionResult About() { … } [Route("Help")] [Route("Home/About")] public IActionResult About() { … } [HttpGet] [Route("Employees/View/{id}")] public IActionResult View(int id) { … } [HttpGet("Employees/View/{id}")] public IActionResult View(int id) { … }
17
Route Constraints Route constraints can be used to restrict how the route parameters are match, e.g. [Route("users/{id:int}")] public User GetUserById(int id) { ... } [Route("users/{name}")] public User GetUserByName(string name) { ... }
18
Mixed Routing A web application can use both conventional and attribute routing Attribute routing takes precedence
19
Example: Add an Employee
Routing based on HTTP request methods Binding Simple type Complex type RedirectToAction() More refactoring-friendly Easier to specify route parameters
20
Binding Map the data in a request to the parameters of an action method Request Add( string name, DateTime dateHired ) Add( Employee employee )
21
Binding Sources Route parameters Query parameters Request body
Posted form fields Uploaded files Objects (e.g. JSON or XML) Request headers Defaults
22
Choosing Binding Source Using Attribute
[FromRoute] [FromQuery] [FromForm] [FromBody] [FromHeader]
23
Binding Collections List<int> numbers numbers=100&numbers=200
Dictionary<string,string> courses courses[4022]=Databases& courses[4050]=DotnetCore courses[0].Key=4022&courses[0].Value=Databases& courses[1].Key=4050&courses[1].Value=DotnetCore
24
Models in MVC Controller Database View MVC Application HTTP request
Domain Model Binding Model View Model Database HTTP response View MVC Application
25
About Model Class It's convenient to use the same model class for the different models, but some sometimes it may be necessary to create separate classes, e.g. to prevent over-posting attack
26
Readings ASP.NET Core in Action: Chapter 4, 5, 6
Routing in ASP.NET Core Model Binding in ASP.NET Core
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.