Sem 2 L2
Sem 2 L2
Application Development
Bishal Gharti Chhetri
[email protected]
Week-2
Agenda
• Controller & Action Method
• Routing
• ActionResult
• Model Binding
• Model Validation
• File(s) upload
| 2
HTTP
Anatomy of an HTTP message
| 4
HTTP Request
| 5
HTTP Response
| 6
Controller & Action Method
ASP.NET Core > Controllers
• A modular and Cohesive approach to API development
• At High Level:
• A class that handles HTTP requests and returns responses.
• Serves as a collection of related API endpoints.
• For example: ProductsController would manage all product-related actions.
• At Low Level:
• Receive HTTP requests and route them to the appropriate action methods.
• Controller groups together action methods that handle specific HTTP requests, facilitating organized and
maintainable code.
| 8
Example
| 9
ASP.NET Core > Action Method
• Public method within a controller that handles incoming HTTP requests and generates appropriate responses.
• Only public methods not marked with the [NonAction] attribute are considered action methods.
• Action methods are associated with specific routes and HTTP verbs. Multiple routes support.
• Action methods can return various types, including:
• Specific Types: Returning a specific data type directly.
• IActionResult: Providing flexibility to return different HTTP status codes and content types.
• ActionResult<T>: Combining a specific return type with HTTP status code results.
• Action methods can be asynchronous, returning Task<IActionResult>, which is beneficial for non-blocking
operations like I/O-bound tasks.
| 10
Example
| 11
Example
| 12
Example
| 13
Example
| 14
Example
| 15
Routing
ASP.NET Core > Routing
• Routing in ASP.NET is the mechanism that maps incoming HTTP requests to the appropriate controller action
methods
• Determines which code should handle a given request based on the URL pattern.
• Handle URL requests in a structured and flexible way.
• Types:
• Conventional Routing
• Attribute Routing
| 17
ASP.NET Core > Routing > Conventional
• Defined in Program.cs (for ASP.NET Core) or RouteConfig.cs (up to ASP.NET MVC 5).
• Follows a predefined pattern.
| 18
ASP.NET Core > Routing > Attribute
• Define routes directly on controller actions using attributes.
• Provides better control and flexibility over routing compared to convention-based routing.
• ASP.NET Core automatically enables attribute routing when using controllers.
• Use attributes from Route Templates.
| 19
ASP.NET Core > HTTP Verb Templates
• An HTTP verb (or HTTP method) defines the action a client wants to perform on a resource in an HTTP request.
• An Http Verb Templates define which HTTP verb (method) an action method in a controller should respond to.
| 20
ASP.NET Core > Route Templates
• All the HTTP Verb Templates are route templates.
• [Route]
• Used for Attribute Routing
• Route Tokens are placeholders in route templates that are replaced with actual values when processing requests.
• [controller]
• [action]
• [area]
| 21
Example
| 22
Action Result
Sending Api Response
ASP.NET Core > ActionResult (Sending Response)
• Represents the outcome of a controller’s action method.
• Encapsulates the details of an HTTP response—including status codes, headers, and any returned data.
• A consistent approach for returning various HTTP responses.
| 24
ASP.NET Core > ActionResult (Sending Response)
ActionResult Method Purpose Status Code
BadRequest() Indicates that the request was invalid or cannot be processed. 400 Bad Request
Unauthorized() Indicates that authentication is required or has failed. 401 Unauthorized
Indicates that the client does not have permission to access the
Forbid() 403 Forbidden
requested resource.
NotFound() Indicates that the requested resource could not be found. 404 Not Found
Indicates a conflict (for example, when attempting to create a
Conflict() 409 Conflict
duplicate resource).
Indicates that the request is well-formed but cannot be processed
UnprocessableEntity() 422 Unprocessable Entity
due to semantic errors.
StatusCode() Returns a response with a custom status code. Custom (as specified)
Returns a standardized error response, typically used for unhandled
Problem() Usually 500 Internal Error
server errors.
| 25
Example
| 26
Example
| 27
Example
| 28
Model Binding
Accessing Request Data
ASP.NET Core > Model Binding
• Process of mapping data from HTTP requests (such as URI parameters (query strings, route data), Body (form data,
JSON) and headers) to action method parameters in a controller.
• Binding To (Destination):
• Simple Types
• Complex Types
| 30
ASP.NET Core > Model Binding >
Binding to Simple Types
• Refers to primitive data types and some basic .NET types.
• Do not have nested or complex structures (like classes or collections).
• Are atomic, can be easily mapped from the incoming HTTP request data.
• ASP.NET can automatically convert incoming request data to these types without needing complex parsing logic.
• Examples:
• Primitive Types : int, float, double, decimal, bool, char, byte, short, long
• String Types : string
• Date and Time Types: DateTime, TimeSpan
• Enumerations (Enums)
• Globally Unique Identifier (GUID)
| 31
ASP.NET Core > Model Binding >
Binding to Complex Types
• User-defined classes, structs, records, or models that are made up of multiple properties, which may themselves be
simple types or other complex types.
• Binding to complex types requires ASP.NET to match each property in the complex type with data from the
incoming request
• Examples:
• Classes or Records: A custom class such as Person that contains properties like Name and Age.
• Structs: Custom structs containing fields like latitude and longitude.
• Arrays and Collections: Arrays or lists of simple or complex types.
• Nested Complex Types: Complex types that contain other complex types as properties (e.g., Order class
containing a Customer class).
| 32
ASP.NET Core > Model Binding > Explicit
• If the default source is incorrect, use one of these attributes to specify the source explicitly:
Attribute Description
[FromQuery] Gets values from the query string.
[FromRoute] Gets values from route data.
[FromForm] Gets values from posted form fields.
[FromBody] Gets values from the request body.
[FromHeader] Gets values from HTTP headers.
| 33
Model Binding Sources > URI Parametrization
• Way to pass additional data via a URI (part of a URL).
• Types:
• Query
• Path/Route
• Matrix
• Fragment (Client-Side Only)
| 34
URI Parametrization > Query String
• Used to send optional key-value pairs in a URL, mainly for filters, sorting, pagination etc.
• Placed after a ? in the URL, Separated by & when multiple parameters are used.
| 35
Example
| 36
URI Parametrization > Path/Route Parameter(s)
• Used to specify a resource.
• Placed directly in the URL path/route, not after a ?.
| 37
URI Parametrization > Route Parameter(s) >
Route Constraints
• To enforce specific rules on route parameters, ensuring they match a particular pattern or condition.
• Helps in handling requests more efficiently and avoiding incorrect URLs reaching controllers.
• Invalid input with constraints results in 404 Not Found.
| 38
URI Parametrization > Route Parameter(s) >
Route Constraints
Constraint Description Example
alpha Matches only alphabetic characters {name:alpha}
min(value) Matches a minimum numeric value {age:min(18)}
max(value) Matches a maximum numeric value {age:max(60)}
length(min, max) Matches string length {code:length(3,10)}
range(min, max) Matches a numeric range {score:range(1,100)}
regex(expression) Matches a regex pattern {phone:regex(^\\d{10}$)}
double Matches a double number {value:double}
| 39
Example
| 40
URL Parametrization > Matrix Parameter(s)
• Less Common, Similar to query parameters.
• Used within specific path segments of a URL and only affect that segment
• Separated by ; instead of ? and &.
• Used in advanced filtering within RESTful services (e.g., JAX-RS in Java).
| 41
URL Parametrization > Fragment
• Everything after fragment identifier: # in a URL.
• Used to navigate to a specific section within a page (i.e. SPA Routing, Deep Linking)
• Not sent to the server; only used by the browser.
| 42
Model Binding Sources > Body
• Bind data from request body.
• Secure Data Transfer: The HTTP body can be encrypted (e.g., using HTTPS).
• Binding Attributes: [FromBody], [FromForm]
• Common (Content-Type) MIME Types for HTTP Body Content:
• application/json (Most commonly used for REST APIs)
• application/x-www-form-urlencoded (For simple form submissions)
• multipart/form-data (For file uploads and complex form data)
• application/octet-stream (Generic binary file transfer)
• text/html (HTML content)
• video/mp4 (MP4 video)
• application/pdf (PDF document)
• image/svg+xml (SVG image)
| 43
Example
| 44
Example
| 45
Example
| 46
Model Validation
Validating HTTP Request data
ASP.NET Core > Model > Validation Attributes
• System.ComponentModel.DataAnnotations namespace provides a variety of attributes for validating data models
in .NET applications.
Attribute Description
[Required] Ensures that a property has a value.
[StringLength] Specifies the minimum and maximum length of a string property.
[Range] Defines the minimum and maximum value for a numerical property.
[RegularExpression] Validates that a property's value matches a specified regular expression pattern.
[EmailAddress] Validates that a property's value is a valid email address format.
[Phone] Ensures that a property's value is a well-formed phone number.
[Url] Validates that a property's value is a well-formed URL.
[CreditCard] Checks that a property's value is a valid credit card number.
| 48
ASP.NET Core > Model > Validation Attributes
Attribute Description
[MaxLength] Specifies the maximum length of an array or string property.
[MinLength] Specifies the minimum length of an array or string property.
[FileExtensions] Validates that a property's value has a valid file extension.
[EnumDataType] Specifies that a data field is associated with an enumeration.
[DataType] Specifies the type of data associated with a data field (e.g., Date, Time, Currency).
[CustomValidation] Allows for custom validation by specifying a method to validate the property or class instance.
[Compare] Compares two properties to ensure they have matching values.
[Base64String] Specifies that a data field value is a well-formed Base64 string.
[AllowedValues] Specifies a list of values that should be allowed in a property.
[DeniedValues] Specifies a list of values that should not be allowed in a property.
| 49
Example
| 50
Example
| 51
File Upload(s)
ASP.NET Core > Uploading File(s)
• To support file upload(s)
• On the client-side, the HTTP request must include file(s) in the form submission with the Content-Type header
set to MIME type: multipart/form-data, enabling the transmission of large files in multiple parts.
• On the server-side, use the below types to bind the file(s) from the incoming HTTP request:
• To explicitly bind from the form, use the [FromForm] attribute.
Types Description
IFormFile Single file upload
IEnumerable<IFormFile>
Multiple file uploads
IFormFileCollection
| 53
Example
| 54
Example
| 55
| 56