Tag - .NET-Framework

Easy Guide to Cancellation Tokens in .NET
Jan 31, 2024

In this blog I'll show how you can use a CancellationToken in your ASP.NET Core action method to stop execution when a user cancels a request from their browser. This can be useful if you have long running requests that you don't want to continue using up resources when a user clicks "stop" or "refresh" in their browser. What is Cancellation Token in c#?  Cancellation tokens in C# are used to signal that a task or operation should be cancelled. They allow for the cooperative cancellation of a task or operation, rather than aborting it forcibly.  Why Use Cancellation Tokens? Here are some benefits of using cancellation tokens:  Avoid resource leaks by freeing up un-managed resources linked to the task  Stop further processing when a task is no longer needed  Improve responsiveness by quickly responding to cancellations  Easy propagation of cancel requests in child tasks  Without cancellation logic, long-running tasks will continue processing in the background even if no longer needed.  You can use cancellaiontoken in any action method or project. Here I am taking one example of .NET web API.  Here, I have created a web API project in .NET, and the above image shows the default controller for the web API, which includes the WeatherForecastController. In that, I have added some log information and added one 10-second task delay that means when this line is executed it will wait for 10 seconds after the next line is executed.  I have added task delay because it is better to understand CancellationToken.  If we hit the URL /GetWeatherForecast then the request will run for 10s, and eventually will return the message. So now, what happens if the user refreshes the browser, halfway through the request? The browser never receives the response from the first request, but as you can see from the logs, the action method executes to completion twice - once for the first (canceled) request, and once for the second (refresh) request.  Whether this is correct behavior will depend on your application.    ASP.NET Core provides a mechanism for the webserver to signal when a request has been canceled using a CancellationToken. This is exposed as HttpContext.RequestAborted, but you can also inject it automatically into your actions using model binding.  Using CancellationToken in your method  CancellationTokens are lightweight objects that are created by a CancellationTokenSource. When a CancellationTokenSource is cancelled, it notifies all the consumers of the CancellationToken. This allows one central location to notify all of the code paths in your app that cancellation was requested.  When cancelled, the IsCancellationRequested property of the cancellation token will be set to True, to indicate that the CancellationTokenSource has been cancelled.  Lets consider the previous example again. We have a long-running action method . As it as an expensive method, we want to stop executing the action as soon as possible if the request is cancelled by the user.  The following code shows how we can hook into the central CancellationTokenSource for the request, by injecting a CancellationToken into the action method, and passing the parameter to the Task.Delay call.  MVC will automatically bind any CancellationToken parameters in an action method to the HttpContext.RequestAborted token, using the CancellationTokenModelBinder.    This model binder is registered automatically when you call services.AddMvc() (or services.AddMvcCore()) in Startup.ConfigureServices().  With this small change, we can test out our scenario again. We'll make an initial request, which starts the long-running action, and then we'll reload the page. As you can see from the logs below, the first request never completes. Instead the Task.Delay call throws a TaskCancelledException when it detects that the CancellationToken.IsCancellationRequested property is true, immediately halting execution.  Summary Users can cancel requests to your web app at any point, by hitting the stop or reload button on your browser. Typically, your app will continue to generate a response anyway, even though Kestrel won't send it to the user. If you have a long-running action method, then you may want to detect when a request is canceled, and stop execution.  You can do this by injecting a CancellationToken into your action method, which will be automatically bound to the HttpContext.RequestAborted token for the request. You can check this token for cancellation as usual, and pass it to any asynchronous methods that support it. If the request is canceled, an OperationCanceledException or TaskCanceledException will be thrown. 

Hosting a .NET Application on IIS Server
Jan 29, 2024

Hosting your .NET application on an IIS (Internet Information Services) server allows it to be accessed and consumed over the internet by users. IIS is commonly used to host .NET applications and web APIs.  Before you can host the application, ensure you have the following:  A .NET web application or API built (for example using ASP.NET Core)  A Windows Server machine with IIS installed and configured  Permissions to remotely access the server over a network    Follow this step-by-step guide to deploy your .NET Application on the IIS Server seamlessly.  Step 1: Open your .NET Application in Visual Studio  Open your application or project in Visual Studio and build the application.    Step 2 : Publish the Application or project.  Now, Right-click on your project and select the publish option.  Here, select the folder and then click on next, and finish the publish setup.  Now, Click on the publish button to publish your code to one folder.  After, publishing is succeeded click on the open folder. You will see your published code in this folder.    Step 3: Configure IIS on the Server  Carry out these steps to prepare IIS for hosting the application. If IIS is not installed in your system, then first install the IIS on your machine.  Open IIS Manager on the Windows Server  Right-click on the Sites folder and click Add Website                    3. Provide a name for the website, Set the physical path to the app folder, and select a port where you want to host the application.                    4. Click OK to create the new IIS website.   Step 4: Publish code to IIS Server.  Now stop the website and open the folder that you have given in the Physical path while configuring it, by right-clicking on your website and selecting explore.  Now, copy all the published files into your server folder.  Once all the files are copied into the publish folder Start the website and click on Browse*: {Your port} (http) under browse website.  you will see the output of your code on the server.  If your project is based on MVC then Recycle Application pool is required. You can find your Application pool under the Application Pool section. Right-click on your website app pool and click on recycle. Conclusion: Hosting the application on IIS allows it to be reached by users from over the network and the internet. It handles request routing and security layers for serving the application.

Quick Tips: Managing Expired Tokens
Jan 01, 2024

Here, I will explain how to restrict users from using expired tokens in a .NET Core application. Token expiration checks are crucial for ensuring the security of your application.   Here's a general outline of how you can achieve this: 1. Configure Token Expiration: When generating a token, such as a JWT, set an expiration time for the token. This is typically done during token creation. For example, when using JWTs, you can specify the expiration claim:   var tokenDescriptor = new SecurityTokenDescriptor {     Expires = DateTime.Now.AddMinutes(30) // Set expiration time }; 2. Token Validation Middleware: Create middleware in your application to validate the token on each request. This middleware should verify the token's expiration time. You can configure this middleware in the startup or program file on the .NET side.   public void Configure(IApplicationBuilder app, IHostingEnvironment env) {     app.UseMiddleware<TokenExpirationMiddleware>(); } 3. Token Expiration Middleware: Develop middleware to validate the token's expiration time. Take note of the following points: ValidateIssuerSigningKey: Set to true, indicating that the system should validate the issuer signing key. IssuerSigningKey: The byte array represents the secret key used for both signing and verifying the JWT token. ValidateIssuer and ValidateAudience: Set to false, indicating that validation of the issuer and audience is skipped. By setting ClockSkew to TimeSpan.Zero, you specify no tolerance for clock differences. If the current time on the server or client is not precisely within the token's validity period, the token is considered expired.      public class TokenExpirationMiddleware     {         private readonly RequestDelegate _next;         public TokenExpirationMiddleware(RequestDelegate next)         {             _next = next;         }         public async Task Invoke(HttpContext context)         {             // Check if the request has a valid token             var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();             if (token != null)             {                 var tokenHandler = new JwtSecurityTokenHandler();                 var key = Encoding.ASCII.GetBytes("YourSecretKey"); // Replace with your actual secret key of Issuer                 var tokenValidationParameters = new TokenValidationParameters                 {                     ValidateIssuerSigningKey = true,                     IssuerSigningKey = new SymmetricSecurityKey(key),                     ValidateIssuer = false,                     ValidateAudience = false,                     ClockSkew = TimeSpan.Zero                 };                 try                 {                     // Validate the token                     var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);                     // Check if the token is expired                     if (securityToken is JwtSecurityToken jwtSecurityToken)                     {                         if (jwtSecurityToken.ValidTo < DateTime.Now)                         {                             // Token is expired                             context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;                             return;                         }                     }                 }                 catch (SecurityTokenException)                 {                     // Token validation failed                     context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;                     return;                 }             }             await _next(context);         }     } Working fine with proper token time. Here is an example: I am providing an expired token, and it will result in a 401 Unauthorized status. You can also check the token in https://jwt.io/ for time expired (exp) . By following these steps, you can effectively implement checks to ensure that users are not able to use expired tokens within your .NET Core application.

magnusminds website loader