





















































Snyk’s annual Capture the Flag event, Fetch the Flag 2025, is back! Hosted by Snyk and John Hammond, the event will take place on February 27, 2025, from 9am ET to 9pm ET. Engage in 20+ real-world security challenges, enhance your professional development & earn CPE credits.
Hi ,
Welcome to a brand new issue of ProgrammingPro.
In today’sExpert Insight, we bring you an excerpt from the recently published book, ASP.NET Core 9.0 Essentials, which covers best practices for handling HTTP requests, including input validation and sanitization, asynchronous programming, and using caching and compression.
News Highlights: Rust 1.85.0 brings language and tooling upgrades; Google’s free Gemini Code Assist collects user code by default; AI coding tools may harm code quality, says GitClear; and GitHub Copilot Extensions now integrate external services into IDEs.
My top 5 picks from today’s learning resources:
But there’s more, so dive right in.
Stay Awesome!
Divya Anne Selvaraj
Editor-in-Chief
await
with a custom AsyncMethodBuilder
.modernc.org/tk9.0
Go package to convert Tcl/Tk 9.0 into standalone executables, enabling Go developers to use Tk without C dependencies.unset()
alone is insufficient, and when to rebuild arrays for optimal memory management.Here’s an excerpt from “Chapter 7: Adding Capabilities to Applications" in the book, ASP.NET Core 9.0 Essentials, by Albert S. Tanure, published in January 2024.
The HTTP request is a fundamental component when working with web applications. Proper handling of HTTP requests can significantly impact the performance and reliability ofyour application.
We have already learned about the
types of HTTP verbs and status codes in Chapter 3. However, each HTTP method provided by the application must be treated appropriately, to avoid inconsistencies in the application andavoid vulnerabilities.
Furthermore, the way HTTP requests are made directly impacts the experience of users or consumers ofyour solution.
Let’s understand some good practices related toHTTP requests.
Always validate and sanitize input to prevent security vulnerabilities such as SQL injection andcross-sitescripting(XSS).XSS is a security vulnerability where the attacker injects scripts into web pages. To know more, gotohttps://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting?view=aspnetcore-9.0.
Consider a scenario where a user submits a form with a username. To prevent harmful data from being processed, you should validate the input to ensure it meets the expected criteria and sanitize it to remove anymalicious content:
public IActionResult Submit(string username)
{
if (string.IsNullOrEmpty(username))
{
return BadRequest("Username is required.");
}
username = HttpUtility.HtmlEncode(username);
// Proceed with processing the username
return Ok();
}
The preceding code demonstrates a simple validation of the username parameter,if(string.IsNullOrEmpty)
, avoiding using it incorrectly. TheHttpUtility.HtmlEncode(username)
method is used to convert characters such as<
,>
,&
, and so on into anHTML-encoded format.
During the execution flow of an HTTP request, we must avoid making the processing actions synchronous. Otherwise, this could degrade the user experience and cause some problems for the application, such asthe following:
It is a recommendation and good practice to use asynchronous methods to improve performance and scalability. For example, when using theHttpClient
object to make a request in an API, use theHttpClient.SendAsync
method insteadofHttpClient.Send
.
Asynchronous programming allows your application to handle multiple tasks simultaneously without waiting for each task to complete before starting the next one. This is similar to how a chef in a busy kitchen might prepare multiple dishes at once, rather than finishing one dish beforestarting another.
We will cover the use of asynchronous programming in more detail in theAsynchronous requests and I/O optimizationsection. Now, let’s understand another good practice in relation to HTTP requests, regarding cachingand compression.
Requests via the HTTP protocol have some attributes, including headers and body. During communication between an application and the backend, this information is transmitted, and the headers are used both by the client (in this case, the browser) and bythe backend.
There are several types of HTTP headers, including those associated with cachingandcompression.
By utilizing caching and response compression, we can reduce bandwidth usage and improve load times. Browsers also identify these headers, avoiding unnecessary requests tothe server.
Caching and dating compression work similarly to how alibrary might keep frequently borrowed books readily accessible or how a vacuum-sealed package takes up less space. These practices reduce the load on your server and speed up responses touser requests.
Let’s analyze the following code snippet extracted from aProgram.cs
class:
// Add services to the container. builder.Services.AddResponseCaching();
app.UseResponseCaching();
app.Use(async (context, next) => {
context.Response.GetTypedHeaders().CacheControl =
new Microsoft.Net.Http.Headers.CacheControlHeaderValue
{
Public = true, MaxAge = TimeSpan.FromMinutes(10)
};
await next();
});
Let’s understand the preceding code. When you addapp.UseResponseCaching
to the application’smiddlewarepipeline, it performs thefollowing functions:
Theapp.Use(async (context, next)
method adds the necessary parameters for the Cache-Control header to the middleware pipeline, such as the cache duration time. This is necessary so that the client can know how the response shouldbe cached.
The cache is managed in the application’s memory and, therefore, it is not interesting to keep the cache for a large amount of time in memory, which could cause problems. However, it is good practice to use it. We will go into more detail about cache usage in the next section,Improving performance with a cache strategy and making theapplication resilient.
ASP.NET Core 9.0 Essentialswas published in December 2024. Packt library subscribers can continue reading the entire book for free or you can buy the book here!
That’s all for today.
We have an entire range of newsletters with focused content for tech pros. Subscribe to the ones you find the most usefulhere.
If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want toadvertise with us.
If you have any suggestions or feedback, or would like us to find you a learning resource on a particular subject, just respond to this email!