Lesson 3 |
ASP.NET Core Objects and the Client-Server Dialogue |
Objective |
Explain how ASP.NET Core's features assist the client-server communication model. |
ASP.NET Core and the Client-Server Dialogue
When a user interacts with a web application, their browser sends HTTP requests to a web server. ASP.NET Core provides a modern, middleware-driven approach to handling these requests. Through services like HttpContext, developers can read, modify, and respond to requests in a structured and consistent manner. This approach replaces the older object model of Classic ASP, delivering better scalability, security, and testability.
Accessing Request Data
ASP.NET Core provides structured access to data submitted through forms or query strings via the HttpRequest object. These collections are dictionary-like and automatically adjust to the incoming data.
To access a single form value:
string firstName = Request.Form["FirstName"];
To access a query string value:
string productId = Request.Query["id"];
To loop through all form fields submitted in a request:
foreach (var key in Request.Form.Keys)
{
var value = Request.Form[key];
Console.WriteLine($"{key} : {value}");
}
Formatting the Response
The HttpResponse object in ASP.NET Core allows you to control what is returned to the browser. This includes setting the ContentType header and writing directly to the output stream.
To return a JSON response with a custom content type:
Response.ContentType = "application/json";
await Response.WriteAsync("{\"status\":\"ok\"}");
Writing Output with Methods
In ASP.NET Core, methods such as Content(), Json(), and View() define how responses are sent to the client. Unlike Classic ASP, output is handled through controller actions or middleware logic.
Here’s a simple example of returning plain text:
public IActionResult GreetUser()
{
return Content("Hello World", "text/plain");
}
Managing Session and Application State
Web applications must handle data for many users at once. ASP.NET Core supports session state management using built-in services. Session variables are stored per user and can persist across multiple requests.
To store a value in session:
HttpContext.Session.SetString("UserName", "Thomas");
To retrieve a value from session:
string user = HttpContext.Session.GetString("UserName");
> Note: Session support must be explicitly enabled in your app’s startup configuration.
Summary
ASP.NET Core represents a significant evolution from Classic ASP. Its modern approach using middleware, dependency injection, and strongly-typed objects allows developers to build scalable, maintainable, and secure web applications. The foundational components—HttpRequest, HttpResponse, session state, and output methods—are essential for mastering client-server interactions in ASP.NET Core 9.0.
