<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Valentyn Osidach 📚 on Medium]]></title>
        <description><![CDATA[Stories by Valentyn Osidach 📚 on Medium]]></description>
        <link>https://medium.com/@valentin.osidach?source=rss-40144240e6f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lqcAwhp0urjZUuHzdtzk2g@2x.jpeg</url>
            <title>Stories by Valentyn Osidach 📚 on Medium</title>
            <link>https://medium.com/@valentin.osidach?source=rss-40144240e6f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:25:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valentin.osidach/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JWT Token Authentication with AppUser in .NET 8]]></title>
            <link>https://medium.com/@valentin.osidach/jwt-authentication-6d955d18d7d7?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d955d18d7d7</guid>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 06:02:07 GMT</pubDate>
            <atom:updated>2024-10-23T06:02:07.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>JWT Token Authentication with AppUser in .NET 8</h3><figure><img alt="JWT Auth token" src="https://cdn-images-1.medium.com/max/1024/1*CawwHRjraPh3fp31cb8QnA.png" /><figcaption>JWT auth token</figcaption></figure><h3>Introduction</h3><p><strong>JWT </strong>authentication is one of the standard ways to secure APIs. This allows for stateless authentication since signed tokens are passed between a client and a server. In .NET 8, there were improvements in how you would work with JWT tokens. Integrating them with an AppUser class would give your application seamless authentication. This article describes the process of implementing JWT token authentication through the class AppUser in a .NET 8 web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yYjp9VPFKu94zZCC0TpLA.png" /><figcaption>Diagram with User flow</figcaption></figure><h3>What is JSON Web Token?</h3><blockquote>JSON Web Token (JWT) is an open standard (<a href="https://tools.ietf.org/html/rfc7519">RFC 7519</a>) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the <strong>HMAC</strong> algorithm) or a public/private key pair using <strong>RSA</strong> or <strong>ECDSA</strong>.</blockquote><blockquote>Although JWTs can be encrypted to also provide secrecy between parties, we will focus on <em>signed</em> tokens. Signed tokens can verify the <em>integrity</em> of the claims contained within it, while encrypted tokens <em>hide</em> those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.</blockquote><h3>What is the JSON Web Token structure?</h3><p>In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:</p><ul><li>Header</li><li>Payload</li><li>Signature</li></ul><p>Therefore, a JWT typically looks like the following.</p><p>xxxxx.yyyyy.zzzzz</p><p>More details at <a href="https://jwt.io/introduction">https://jwt.io/introduction</a></p><h3>Setting Up JWT Token Authentication</h3><h4>1. Create a New .NET 8 Web API Project</h4><pre>dotnet new webapi -n JwtAuthApp</pre><h4><strong>2.</strong> Install Required NuGet Packages</h4><pre>dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer<br>dotnet add package Microsoft.IdentityModel.Tokens</pre><h4>3. Create a JWT Configuration model</h4><pre>using System.Globalization;<br><br>namespace JwtAuthApp.JWT;<br><br>public class JwtConfiguration<br>{<br>    public string Issuer { get; } = string.Empty;<br><br>    public string Secret { get; } = string.Empty;<br><br>    public string Audience { get; } = string.Empty;<br><br>    public int ExpireDays { get; }<br><br>    public JwtConfiguration(IConfiguration configuration)<br>    {<br>        var section = configuration.GetSection(&quot;JWT&quot;);<br><br>        Issuer = section[nameof(Issuer)];<br>        Secret = section[nameof(Secret)];<br>        Audience = section[nameof(Secret)];<br>        ExpireDays = Convert.ToInt32(section[nameof(ExpireDays)], CultureInfo.InvariantCulture);<br>    }<br>}</pre><h4>4. Add JWT Configuration to your app.settings</h4><pre>{<br>  &quot;Jwt&quot;: {<br>    &quot;Issuer&quot;: &quot;JwtAuthApp&quot;,<br>    &quot;Audience&quot;: &quot;https://localhost:7031/&quot;,<br>    &quot;Secret&quot;: &quot;70FC177F-3667-453D-9DA1-AF223DF6C014&quot;,<br>    &quot;ExpireDays&quot;: 30<br>  }<br>}</pre><ul><li>❗️<strong>Issuer</strong>: Identifies the principal who issued the token (typically your application).</li></ul><p><strong>Audience</strong>: Specifies who the token is intended for (usually the clients or services consuming the API).</p><ul><li>❗️<strong>Secret</strong>: A key is used to sign the JWT to ensure its authenticity. It should be a long and random string to prevent tampering.</li><li><strong>ExpireDays</strong>: Defines how long the token will be valid before it expires.</li></ul><h4>5. Configure DI for the Configuration in Program.cs</h4><pre>builder.Services.AddTransient&lt;JwtConfiguration&gt;();</pre><h4>6. Configure JWT Authentication Extensions</h4><pre>using Microsoft.AspNetCore.Authentication;<br>using Microsoft.AspNetCore.Authentication.JwtBearer;<br>using Microsoft.AspNetCore.DataProtection;<br>using Microsoft.IdentityModel.Tokens;<br>using System.ComponentModel.DataAnnotations;<br>using System.Diagnostics.Metrics;<br>using System.Security.Claims;<br>using System;<br>using System.Text;<br><br>namespace JwtAuthApp.JWT;<br><br>public static class JwtAuthBuilderExtesnions<br>{<br>    public static AuthenticationBuilder AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration)<br>    {<br>        var jwtConfiguration = new JwtConfiguration(configuration);<br><br>        services.AddAuthorization();<br><br>        return services.AddAuthentication(x =&gt;<br>        {<br>            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;<br>            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;<br>        })<br>        .AddJwtBearer(x =&gt;<br>        {<br>            x.SaveToken = true;<br>            x.TokenValidationParameters = new TokenValidationParameters<br>            {<br>                ValidateIssuer = true,<br>                ValidateAudience = true,<br>                ValidateLifetime = true,<br>                ValidateIssuerSigningKey = true,<br>                ValidIssuer = jwtConfiguration.Issuer,<br>                ValidAudience = jwtConfiguration.Audience,<br>                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfiguration.Secret)),<br><br>                RequireExpirationTime = true,<br>            };<br>            x.Events = new JwtBearerEvents<br>            {<br>                OnMessageReceived = context =&gt;<br>                {<br>                    string authorization = context.Request.Headers[&quot;Authorization&quot;];<br><br>                    if (string.IsNullOrEmpty(authorization))<br>                    {<br>                        context.NoResult();<br>                    }<br>                    else<br>                    {<br>                        context.Token = authorization.Replace(&quot;Bearer &quot;, string.Empty);<br>                    }<br><br>                    return Task.CompletedTask;<br>                },<br>            };<br>        });<br>    }<br>}</pre><ul><li><strong>SaveToken</strong>: Defines whether the bearer token should be stored in the AuthenticationProperties after a successful authorization.</li><li>❗️<strong>ValidateIssuer: </strong>Ensures that the token’s iss (issuer) claim matches the expected issuer.</li><li><strong>ValidateAudience</strong>: Validates the aud (audience) claim in the token to make sure it matches the expected audience.</li><li><strong>ValidateLifetime</strong>: Checks that the token’s exp (expiration) time is valid, the token hasn&#39;t expired.</li><li>❗️<strong>ValidateIssuerSigningKey</strong>: Verifies the token’s signature against the signing key to ensure its integrity.</li><li>❗️<strong>ValidIssuer</strong>: Specifies the expected issuer for the token, pulled from the configuration (appsettings.json or environment variables).</li><li>❗️<strong>IssuerSigningKey</strong>: Uses a symmetric security key to sign and validate the JWT, converting the secret key from the configuration into a byte array for encryption.</li><li><strong>RequireExpirationTime</strong>: Ensures that the JWT token contains the exp (expiration) claim.</li><li><strong>OnMessageReceived</strong>: save token in context</li></ul><p>❗️ <strong>=</strong> <strong>Important</strong></p><h4>7. Configure JWT Authentication in Program.cs</h4><pre><br><br>builder.Services.AddJwtAuthentication(builder.Configuration);<br><br><br>app.UseAuthentication();<br>app.UseAuthorization();</pre><h4>8. Create the Token Generation Service</h4><pre>using Microsoft.IdentityModel.Tokens;<br>using System.IdentityModel.Tokens.Jwt;<br>using System.Security.Claims;<br>using System.Text;<br><br>namespace JwtAuthApp.JWT;<br><br>public class TokenService<br>{<br>    private readonly JwtConfiguration _config;<br><br>    public TokenService(JwtConfiguration config)<br>    {<br>        _config = config;<br>    }<br><br>    public string GenerateToken(string id, string email)<br>    {<br>        var claims = new[]<br>        {<br>            new Claim(JwtRegisteredClaimNames.Sub, id),<br>            new Claim(JwtRegisteredClaimNames.Email, email),<br>            // Add more claims if needed<br>        };<br><br>        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.Secret));<br>        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);<br><br>        var token = new JwtSecurityToken(<br>            issuer: _config.Issuer,<br>            audience: _config.Audience,<br>            claims: claims,<br>            expires: DateTime.Now.AddDays(_config.ExpireDays),<br>            signingCredentials: creds<br>        );<br><br>        return new JwtSecurityTokenHandler().WriteToken(token);<br>    }<br>}</pre><p>I do not recommend storing information such as First Name, Last Name, Role, and other data in a token.</p><h4>9. Register Token Service</h4><pre>builder.Services.AddTransient&lt;TokenService&gt;();</pre><h4>10. Add Login Endpoint or Controller with Login</h4><pre>app.MapPost(&quot;/login&quot;, (LoginRequest request, TokenService tokenService) =&gt;<br>{<br>    // In a real app, you would validate the user&#39;s credentials against a database.<br>    // Authenticate user and generate token <br>    // For demo purposes, we are using hardcoded values<br>    var userIsAuthenticated = request.Username == &quot;admin&quot; &amp;&amp; request.Password == &quot;admin&quot;;<br><br>    if (!userIsAuthenticated)<br>    {<br>        return Results.Unauthorized();<br>    }<br>    var userId = &quot;9999&quot;; // Get user id from database<br>    var email = &quot;valentin.osidach@gmail.com&quot;; // Get email from database<br>    var token = tokenService.GenerateToken(userId, email);<br><br>    return Results.Ok(token);<br>}).AllowAnonymous();</pre><p><strong>11. Add SwaggerConfiguration</strong> (For easy testing)</p><pre>using Microsoft.OpenApi.Models;<br>using Swashbuckle.AspNetCore.SwaggerGen;<br><br>namespace JwtAuthApp.JWT;<br><br>public static class SwaggerConfiguration<br>{<br>    public static OpenApiSecurityScheme Scheme =&gt; new OpenApiSecurityScheme<br>    {<br>        In = ParameterLocation.Header,<br>        Description = &quot;Please enter a valid token&quot;,<br>        Name = &quot;Authorization&quot;,<br>        Type = SecuritySchemeType.Http,<br>        BearerFormat = &quot;JWT&quot;,<br>        Scheme = &quot;Bearer&quot;,<br>        Reference = new OpenApiReference<br>        {<br>            Id = &quot;Bearer&quot;,<br>            Type = ReferenceType.SecurityScheme,<br>        },<br>    };<br><br>    public static void Configure(SwaggerGenOptions option)<br>    {<br>        option.ResolveConflictingActions(apiDesc =&gt; apiDesc.First());<br>        option.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;API&quot;, Version = &quot;v1&quot; });<br>        option.AddSecurityDefinition(Scheme.Reference.Id, Scheme);<br>        option.AddSecurityRequirement(new OpenApiSecurityRequirement<br>        {<br>            { Scheme, Array.Empty&lt;string&gt;() },<br>        });<br>    }<br>}</pre><pre>builder.Services.AddSwaggerGen(SwaggerConfiguration.Configure);</pre><h4>12. Add AppUser</h4><pre>public class AppUser : ClaimsPrincipal<br>{<br>    public AppUser(IHttpContextAccessor contextAccessor) : base(contextAccessor.HttpContext.User) { }<br><br>    public string Id =&gt; FindFirst(ClaimTypes.NameIdentifier).Value;<br>    public string Email =&gt; FindFirst(ClaimTypes.Email).Value;<br>}</pre><pre>builder.Services.AddTransient&lt;AppUser&gt;();<br>builder.Services.AddHttpContextAccessor();</pre><h4>13. Add Authorize attribute to all Controllers or endpoints</h4><pre>app.MapGet(&quot;/weatherforecast&quot;, () =&gt;<br>{<br>    var forecast = Enumerable.Range(1, 5).Select(index =&gt;<br>        new WeatherForecast<br>        (<br>            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),<br>            Random.Shared.Next(-20, 55),<br>            summaries[Random.Shared.Next(summaries.Length)]<br>        ))<br>        .ToArray();<br>    return forecast;<br>})<br>.RequireAuthorization()<br>.WithName(&quot;GetWeatherForecast&quot;)<br>.WithOpenApi();<br><br>//Inject AppUser and get user email from the token <br>app.MapGet(&quot;/user&quot;, (AppUser user) =&gt;<br>{<br>    return Results.Ok(user.Email);<br>})<br>.RequireAuthorization()<br>.WithName(&quot;GetUserEmail&quot;)<br>.WithOpenApi();</pre><h3>Testing</h3><ul><li>All endpoints</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySdyMYl2wYMzDkjH3WYghg.png" /></figure><ul><li>Get weatherforecast got error 401 (Unauthorize) before login</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3PXhZeUay20V1g_PTnQcg.png" /></figure><ul><li>Login returned jwt token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4W0_wEBYYoDpZkkig-q_sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkZ4UAs5eyvwNGlltSqp3g.png" /></figure><p>Response token : <br>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5OTk5IiwiZW1haWwiOiJ2YWxlbnRpbi5vc2lkYWNoQGdtYWlsLmNvbSIsImV4cCI6MTczMjIxMTM5OSwiaXNzIjoiSnd0QXV0aEFwcCIsImF1ZCI6IjcwRkMxNzdGLTM2NjctNDUzRC05REExLUFGMjIzREY2QzAxNCJ9.YCBGUFiGFKMZCJJL3sgsk-1lbruSnuY2lWpY71SLx3Y</p><ul><li>Using jwt token in Swagger Auth</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*GgT5-DacFh-dh52zxW96PQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*v7oX_jry2i6FSu_ZPce9zg.png" /></figure><ul><li>Get weather forecast return result</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33yea3Z8sQBJ95OSKrx0HA.png" /></figure><ul><li>Get user email return user email</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EF_bhMT9biZ2hBUAVp7VnA.png" /></figure><ul><li><a href="https://medium.com/@valentin.osidach/list/aeeed1ecd4c8">Most popular C# articles</a></li><li><a href="https://github.com/RavenValentin/AppUserWithJwt">GitHub - RavenValentin/AppUserWithJwt</a></li><li><a href="https://jwt.io/">JSON Web Tokens - jwt.io</a></li></ul><h3>Conclusion</h3><p>In this article, we demonstrated how to implement JWT token authentication using a minimal API structure in .NET 8. This approach offers a simple and clean way to secure your APIs without the overhead of controllers. The key steps include configuring JWT authentication, generating tokens, and protecting endpoints with minimal code.</p><p>With this setup, you can further expand the authentication flow by adding more features like user registration, token refresh, or role-based authorization.</p><p>👏 Enjoyed the article? Hit follow to stay updated and show your support!</p><p>💬 Think I missed something? Drop your thoughts in the comments or reach out to me directly — I’d love to hear your feedback.</p><p>⬇️ Dive into my other articles for more insights and tips.</p><p>💬 Spot any errors or have additional ideas? Let me know in the comments — I appreciate every bit of input!</p><p>👥 Found this interesting? Share it with a friend and spark a discussion. Sometimes the best insights come from a good debate.</p><p>🚀 Keep pushing forward, stay inspired, and never stop learning.</p><p><strong>Thank you for reading!</strong></p><p>Program file:</p><pre>using JwtAuthApp.JWT;<br>using Microsoft.AspNetCore.Authorization;<br>using System.Security.Claims;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br>builder.Services.AddHttpContextAccessor();<br><br>builder.Services.AddTransient&lt;JwtConfiguration&gt;();<br>builder.Services.AddTransient&lt;TokenService&gt;();<br>builder.Services.AddTransient&lt;AppUser&gt;();<br><br>// Add JWT Authentication configuration<br>builder.Services.AddJwtAuthentication(builder.Configuration);<br>builder.Services.AddSwaggerGen(SwaggerConfiguration.Configure);<br><br>var app = builder.Build();<br><br>app.UseAuthentication();<br>app.UseAuthorization();<br><br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br><br>var summaries = new[]<br>{<br>    &quot;Freezing&quot;, &quot;NY&quot;, &quot;Chilly&quot;, &quot;Cool&quot;, &quot;Mild&quot;, &quot;Warm&quot;, &quot;Balmy&quot;, &quot;Hot&quot;, &quot;Sweltering&quot;, &quot;Lviv&quot;<br>};<br><br><br>app.MapPost(&quot;/login&quot;, (LoginRequest request, TokenService tokenService) =&gt;<br>{<br>    // In a real app, you would validate the user&#39;s credentials against a database.<br>    // Authenticate user and generate token <br>    // For demo purposes, we are using hardcoded values<br>    var userIsAuthenticated = request.Username == &quot;admin&quot; &amp;&amp; request.Password == &quot;admin&quot;;<br><br>    if (!userIsAuthenticated)<br>    {<br>        return Results.Unauthorized();<br>    }<br>    var userId = &quot;9999&quot;; // Get user id from database<br>    var email = &quot;valentin.osidach@gmail.com&quot;; // Get email from database<br>    var token = tokenService.GenerateToken(userId, email);<br><br>    return Results.Ok(token);<br>}).AllowAnonymous();<br><br>app.MapGet(&quot;/weatherforecast&quot;, () =&gt;<br>{<br>    var forecast = Enumerable.Range(1, 5).Select(index =&gt;<br>        new WeatherForecast<br>        (<br>            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),<br>            Random.Shared.Next(-20, 55),<br>            summaries[Random.Shared.Next(summaries.Length)]<br>        ))<br>        .ToArray();<br>    return forecast;<br>})<br>.RequireAuthorization()<br>.WithName(&quot;GetWeatherForecast&quot;)<br>.WithOpenApi();<br><br>//get user email from token <br>app.MapGet(&quot;/user&quot;, [Authorize] (AppUser user) =&gt;<br>{<br>    return Results.Ok(user.Email);<br>})<br>.RequireAuthorization()<br>.WithName(&quot;GetUserEmail&quot;)<br>.WithOpenApi();<br><br>app.Run();<br><br>public class LoginRequest<br>{<br>    public string Username { get; set; } = string.Empty;<br>    public string Password { get; set; } = string.Empty;<br>}<br><br>public record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)<br>{<br>    public int TemperatureF =&gt; 32 + (int)(TemperatureC / 0.5556);<br>}<br><br>public class AppUser : ClaimsPrincipal<br>{<br>    public AppUser(IHttpContextAccessor contextAccessor) : base(contextAccessor.HttpContext.User) { }<br><br>    public string Id =&gt; FindFirst(ClaimTypes.NameIdentifier).Value;<br>    public string Email =&gt; FindFirst(ClaimTypes.Email).Value;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d955d18d7d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Productivity: Create and Use Custom C# Class Templates in Visual Studio ]]></title>
            <link>https://medium.com/@valentin.osidach/custom-class-templates-in-visual-studio-d53b24fa3907?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d53b24fa3907</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 06:01:56 GMT</pubDate>
            <atom:updated>2024-10-08T06:01:56.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Boost Productivity: Create and Use Custom C# Class Templates in Visual Studio</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrAhVxRqNZHkH4D9zLc25A.png" /></figure><h3>Introduction</h3><p>Custom C# Class Templates can be used to increase the speed and quality of code writing, allowing you to reuse code structures, patterns, and configurations.</p><p>You can create a custom template in Visual Studio by making your template file, editing it accordingly, and then exporting it into a reusable template format. This comes out in the ‘Add New Item’ dialog and can be used throughout different projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*R5k4LyAT3yW4A9wCtDmL_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*kCHc2hMLEJpZ8vB7jni51w.png" /></figure><h3>Creating a New Project</h3><p><em>❕You can skip these steps and use an existing project</em></p><h4>1. Open Visual Studio</h4><h4>2. Create a New Project</h4><ul><li>Click on <strong>File &gt; New &gt; Project…</strong> to open the project creation dialog.</li><li>In the <strong>Create a new project</strong> window, select a project type (e.g., <strong>Console App</strong>, <strong>Class Library</strong>, etc.). For this tutorial, we will use a <strong>Console App</strong> in <strong>C#</strong>.</li></ul><h4>3. Configure Your Project</h4><ul><li>In the <strong>Configure your new project</strong> screen:</li><li><strong>Project Name</strong>: Enter a project name (e.g. TemplateDemo).</li><li><strong>Solution Name</strong>: This can be the same as your project name or something different if you plan to add multiple projects to the solution.</li></ul><h3>Creating a New Template class</h3><h4>1. Add new class</h4><ul><li>Click on <strong>Project &gt; Add new item &gt; Change File name &gt; Add (</strong>e.g.EntityTemplate<strong>)</strong></li></ul><h4>2. Update class with template</h4><ul><li>Modify the default code to reflect your needs.</li></ul><pre>using System.ComponentModel;<br><br>namespace $rootnamespace$;<br><br>[Description(&quot;$safeitemrootname$&quot;)]<br>public class $safeitemrootname$<br>{<br>    public int Id { get; set; }<br>    // Add default properties, methods, or regions if needed<br>}</pre><p>This template will create a new c# class <strong>Product.cs</strong></p><pre>using System.ComponentModel;<br><br>namespace TemplateDemo;<br><br>[Description(&quot;Product&quot;)]<br>public class Product<br>{<br>    public int Id { get; set; }<br>    // Add default properties, methods, or regions if needed<br>}</pre><h4>All template parameters</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*nlLuzqw2ptUyAEXOGFW4oA.png" /></figure><p><a href="https://learn.microsoft.com/en-us/visualstudio/ide/template-parameters?view=vs-2019#reserved-template-parameters">Project and item template parameters - Visual Studio (Windows)</a></p><h3>Export the File as a Template</h3><ol><li><strong>Save your file</strong> and make sure it’s in the desired state for your template.</li><li><strong>Export the Template</strong>:</li></ol><ul><li>Go to the top menu and click on <strong>Project &gt; Export Template…</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*ZkxtYdxX3_Gj-S3UkM0a6Q.png" /></figure><ul><li>You’ll have two options:</li><li><strong>Project Template</strong>: Exports the entire project.</li><li><strong>Item Template</strong>: Exports just one file (this is what you want).</li><li>Select <strong>Item Template</strong> and click <strong>Next</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*ZvNaMJBkGeL3NDNJyMWPmA.png" /></figure><p><strong>3. Select the File to Export</strong>:</p><ul><li>Choose the specific file(s) from the project that you want to include in the template. (EntityTemplate)</li><li>Click <strong>Next</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*35GsHhWBPBc5SsqLfNtWHA.png" /></figure><p><strong>4. Provide a Template Name and Details</strong>:</p><ul><li>Give your template a name (e.g., EntityClass).</li><li>Optionally, provide a description, choose an icon, and set any other metadata.</li><li>Mark as Automatically import the template into Visual Studio</li><li>Click <strong>Finish</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*gCgJnaLNQV-UcMeP4-OjXw.png" /></figure><p><strong>5. Locate the Exported Template</strong>:</p><ul><li>Once the template is exported, it will be saved in the Visual Studio templates folder with EntityClass.zipname, usually in:</li></ul><pre>%USERPROFILE%\Documents\Visual Studio &lt;version&gt;\My Exported Templates<br>%USERPROFILE%\Documents\Visual Studio &lt;version&gt;\Templates\ItemTemplates<br><br><br>%USERPROFILE%\Documents\Visual Studio 2022\My Exported Templates<br>%USERPROFILE%\Documents\Visual Studio 2022\Templates\ItemTemplates</pre><p><strong><em>❕You can copy this template to other machines or share it with your team.</em></strong></p><h3>Use the Custom Template</h3><ol><li><strong>Restart the Visual Studio</strong></li><li><strong>Add the Custom Template to Visual Studio</strong>:</li></ol><ul><li>After exporting, the template will automatically be available in the <strong>“Add New Item”</strong> dialog in Visual Studio.</li></ul><p><strong>3. Adding a New Item</strong>:</p><ul><li>In the Solution Explorer, right-click on a project or folder and select <strong>Add &gt; New Item…</strong>.</li><li>In the <strong>New Item</strong> dialog, your custom template will appear under the category <strong>Visual C# Items</strong> (or the relevant language category).</li><li>Select your custom template, give the new file a name, and click <strong>Add</strong>.</li><li>Visual Studio will generate a new file using your custom template.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*rilzG9zTToJKBCINjgyWdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*StP5aMftxkwcBZD_23KNKw.png" /></figure><h3>Customize the Template (Optional)</h3><p>If you want more control over the template’s behavior, you can manually edit the .vstemplate file associated with your custom template.</p><ol><li><strong>Locate the Template</strong>:</li></ol><ul><li>The .vstemplate file is typically found in the zip file that Visual Studio creates when exporting the template (in the path mentioned above).</li></ul><p><strong>2. Open the </strong><strong>.vstemplate File</strong>:</p><ul><li>Open the .vstemplate file in a text editor.</li><li>You can modify things like:</li><li>Default file names.</li><li>Placeholders for namespaces, class names, etc.</li><li>Additional files to include in the template.</li></ul><pre>&lt;VSTemplate Version=&quot;3.0.0&quot; xmlns=&quot;http://schemas.microsoft.com/developer/vstemplate/2005&quot; Type=&quot;Item&quot;&gt;<br>  &lt;TemplateData&gt;<br>    &lt;DefaultName&gt;EntityClass.cs&lt;/DefaultName&gt;<br>    &lt;Name&gt;EntityClass&lt;/Name&gt;<br>    &lt;Description&gt;&amp;lt;No description available&amp;gt;&lt;/Description&gt;<br>    &lt;ProjectType&gt;CSharp&lt;/ProjectType&gt;<br>    &lt;SortOrder&gt;10&lt;/SortOrder&gt;<br>    &lt;Icon&gt;__TemplateIcon.png&lt;/Icon&gt;<br>  &lt;/TemplateData&gt;<br>  &lt;TemplateContent&gt;<br>    &lt;References /&gt;<br>    &lt;ProjectItem SubType=&quot;&quot; TargetFileName=&quot;$fileinputname$.cs&quot; ReplaceParameters=&quot;true&quot;&gt;EntityTemplate.cs&lt;/ProjectItem&gt;<br>  &lt;/TemplateContent&gt;<br>&lt;/VSTemplate&gt;</pre><h3>Other Features:</h3><ol><li><strong>Project Templates</strong>:</li></ol><ul><li>A <strong>project template</strong> is used to create an entire project based on the defined structure.</li><li>This can include multiple files, project settings, references, and NuGet packages.</li></ul><p>2. <strong>Folder and File Structure</strong></p><ul><li>You can define complex folder structures and file hierarchies inside your template. This allows for organization in your projects, including default directories like Models, Views, or Controllers.</li></ul><pre>&lt;Folder Name=&quot;Models&quot;&gt;<br>   &lt;ProjectItem ReplaceParameters=&quot;true&quot;&gt;UserModel.cs&lt;/ProjectItem&gt;<br>&lt;/Folder&gt;<br>&lt;Folder Name=&quot;Views&quot;&gt;<br>   &lt;Folder Name=&quot;User&quot;&gt;<br>      &lt;ProjectItem ReplaceParameters=&quot;true&quot;&gt;Index.cshtml&lt;/ProjectItem&gt;<br>   &lt;/Folder&gt;<br>&lt;/Folder&gt;<br>&lt;Folder Name=&quot;Controllers&quot;&gt;<br>   &lt;ProjectItem ReplaceParameters=&quot;true&quot;&gt;UserController.cs&lt;/ProjectItem&gt;<br>&lt;/Folder&gt;</pre><p><strong>3. Custom Icons</strong></p><p>You can provide custom icons and preview images for your template, making it easily identifiable in Visual Studio’s project or item creation dialogs.</p><ul><li>Include an image file (e.g., 32x32 for icons and 256x256 for preview thumbnails) in your template directory.</li><li>Reference the icon in the .vstemplate file:</li></ul><pre>&lt;TemplateData&gt;<br>    &lt;Icon&gt;MyTemplateIcon.ico&lt;/Icon&gt;<br>    &lt;PreviewImage&gt;MyTemplatePreview.png&lt;/PreviewImage&gt;<br>&lt;/TemplateData&gt;</pre><p><strong>4. NuGet Package Integration</strong></p><p>You can automatically include <strong>NuGet packages</strong> in your custom project template by defining them in the .vstemplate file or in your .csproj file. When users create a project based on your template, these packages will be installed automatically.</p><p>Example in .csproj:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;<br>   &lt;PropertyGroup&gt;<br>      &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>   &lt;/PropertyGroup&gt;<br>   &lt;ItemGroup&gt;<br>      &lt;PackageReference Include=&quot;Newtonsoft.Json&quot; Version=&quot;13.0.1&quot; /&gt;<br>   &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p>5. <strong>Custom Parameter Prompts and Values</strong></p><ul><li>You can define custom parameters for your templates, asking the user to provide certain values during project creation (e.g., a company name, author, or configuration setting).</li><li>In the .vstemplate file, define custom parameters:</li></ul><pre>&lt;CustomParameter Name=&quot;$customauthor$&quot; Value=&quot;Valentyn Osidash&quot; /&gt;</pre><p>In your template files, reference these parameters:</p><pre>// Created by: $customauthor$</pre><h3>Conclusion</h3><p>Creating custom templates in Visual Studio is a great way to speed up your workflow and keep projects consistent. Instead of setting up the same files and configurations over and over again, you can build templates that do it for you. Whether it’s a full project or just a specific item, templates let you reuse code, structures, and settings easily. Plus, you can customize them with features like placeholders, multi-project setups, and even wizards to gather extra info during project creation. In short, templates save you time and help you start projects quickly, with everything ready to go from the start.</p><p>👏 Enjoyed the article? Hit follow to stay updated and show your support!</p><p>💬 Think I missed something? Drop your thoughts in the comments or reach out to me directly — I’d love to hear your feedback.</p><p>⬇️ Dive into my other articles for more insights and tips.</p><p>💬 Spot any errors or have additional ideas? Let me know in the comments — I appreciate every bit of input!</p><p>👥 Found this interesting? Share it with a friend and spark a discussion. Sometimes the best insights come from a good debate.</p><p>🚀 Keep pushing forward, stay inspired, and never stop learning.</p><p><strong>Thank you for reading!</strong></p><h3>References</h3><ul><li><a href="https://medium.com/@valentin.osidach/list/aeeed1ecd4c8">Most popular C# articles</a></li><li><a href="https://learn.microsoft.com/en-us/visualstudio/ide/how-to-create-item-templates?view=vs-2022">Create item templates with Export Template Wizard - Visual Studio (Windows)</a></li><li><a href="https://learn.microsoft.com/en-us/visualstudio/ide/template-parameters?view=vs-2019">Project and item template parameters - Visual Studio (Windows)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d53b24fa3907" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to easy Convert Between CSV and Excel Files]]></title>
            <link>https://medium.com/c-sharp-programming/convert-between-csv-and-excel-files-2c7ef5993bc0?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c7ef5993bc0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 06:03:01 GMT</pubDate>
            <atom:updated>2024-09-17T06:03:01.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJTFtEzOWEkJ8_6ZOvV8Nw.png" /><figcaption>CSV, Excel</figcaption></figure><blockquote>Learn how to easily convert CSV files to Excel in two lines and back with step-by-step instructions and helpful tips using C# and MiniExcel.</blockquote><h3>Introduction</h3><p>MiniExcel is a lightweight and efficient library for working with Excel files in .NET. In this article, we will explore how to use MiniExcel to read and process Excel files by examining a practical example. This example demonstrates how to analyze sales data across multiple files and generate reports based on extracted information.</p><h3>Prerequisites</h3><p>Before diving into the code, ensure that you have the following:</p><ul><li>.NET installed on your machine.</li><li>The MiniExcel library is installed in your project. You can install it via NuGet using the following command:</li></ul><pre>dotnet add package MiniExcel</pre><p><a href="https://medium.com/@valentin.osidach/list/aeeed1ecd4c8">Most popular C# articles</a></p><h3>Scenario Overview</h3><p>In this example, we have:<br>A books.xlsx file containing product information, including book name, author, price, and quantity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*yKckSwaIDv22JX6hpOSAPg.png" /><figcaption>Excel file with books (Name, AuthorName, Price, Quantity)</figcaption></figure><h4>Our goal is to:</h4><ul><li>Read data from an Excel file.</li><li>Save data as CSV.</li><li>Modify the data by adding a new record.</li><li>Save the modified data into a new Excel file.</li><li>Work with multiple sheets and organize data.</li><li>Sort data by a price field and save the results.</li></ul><h4>Book and Author Classes</h4><pre>class Book<br>{<br>    public string Name { get; set; }<br>    public string Author { get; set; }<br>    public double Price { get; set; }<br>    public int Quantity { get; set; }<br>}<br><br>class Author<br>{<br>    public string Name { get; set; }<br><br>    public Author(string name)<br>    {<br>        Name = name;<br>    }<br>}</pre><h3>Step 1: Reading from an Excel File</h3><p>The first step is to read data from an existing Excel file. The MiniExcel.Query&lt;T&gt;() method is used to query the contents of the Excel file into a collection of objects.</p><pre>// Path to the Excel file<br>var path = @&quot;D:\books.xlsx&quot;;<br>var books = MiniExcel.Query&lt;Book&gt;(path);</pre><p>Here, the Book class represents the structure of each row in the Excel file. MiniExcel reads the file and maps the data into a list of Book objects.</p><h3>Step 2: Saving Results to a CSV File</h3><p>Once the data is loaded, you can save it to a CSV file using the MiniExcel.SaveAsAsync() method.</p><pre>// Save results into a new CSV file<br>var resultCsvPath = @&quot;D:\Results.csv&quot;;<br>await MiniExcel.SaveAsAsync(resultCsvPath, books, excelType: ExcelType.CSV);</pre><p>This code saves the data from the books collection into a CSV file located at D:\Results.csv.</p><h3>Step 3: Reading CSV and Adding a New Book</h3><p>To demonstrate how to modify data, let’s read the CSV file we just created, add a new book, and save the changes back into Excel.</p><pre>// Read CSV then add a new book<br>var newBooks = MiniExcel.Query&lt;Book&gt;(resultCsvPath).ToList();<br>newBooks.Add(new Book { Name = &quot;C# 12.0&quot;, Author = &quot;Anders&quot;, Price = 20, Quantity = 100 });</pre><p>The MiniExcel.Query&lt;Book&gt;() method is used to read the CSV file back into a list. After that, a new Book object is added to the list.</p><h3>Step 4: Saving the Modified Data as a New Excel File</h3><p>Once the new book is added, you can save the updated list of books into a new Excel file.</p><pre>// Save the new books in a new Excel file<br>var newResultPath = @&quot;D:\NewResults.xlsx&quot;;<br>await MiniExcel.SaveAsAsync(newResultPath, newBooks);</pre><p>The updated data is now saved in a new Excel file called NewResults.xlsx.</p><h3>Step 5: Saving Multiple Sheets in a Single Excel File</h3><p>To demonstrate how to work with multiple sheets, we will save the list of books on one sheet and the list of unique authors on another sheet.</p><pre>// Save Excel with authors in one sheet and books in another<br>var newResultPath2 = @&quot;D:\NewResults2.xlsx&quot;;<br>var sheets = new Dictionary&lt;string, object&gt;<br>{<br>    [&quot;Books&quot;] = newBooks,<br>    [&quot;Authors&quot;] = newBooks.Select(x =&gt; new Author(x.Author)).Distinct(),<br>};<br>await MiniExcel.SaveAsAsync(newResultPath2, sheets);</pre><p>In this example, we create two sheets: one for the books and one for the authors. Each sheet is represented as a key-value pair in the dictionary, with the sheet name as the key and the data as the value.</p><h3>Step 6: Sorting and Saving the Data</h3><p>Finally, we’ll sort the books by price and save the sorted data into a new Excel file.</p><pre>// Sort by price then save<br>var newResultPath3 = @&quot;D:\NewResults3.xlsx&quot;;<br>await MiniExcel.SaveAsAsync(newResultPath3, newBooks.OrderBy(x =&gt; x.Price));</pre><p>We use LINQ to sort the books by price in ascending order before saving them.</p><p><a href="https://medium.com/@valentin.osidach/list/aeeed1ecd4c8">Most popular C# articles</a></p><h3>Conclusion</h3><p>Working with Excel and CSV files doesn’t have to be complicated. With the <strong>MiniExcel</strong> library, you can easily read, write, and manipulate data in just a few lines of C# code. Whether you need to convert between formats, update existing data, or work with multiple sheets, MiniExcel simplifies these tasks, allowing you to focus on what matters — managing and analyzing your data. Its lightweight and easy-to-use nature makes it a powerful tool for any developer looking to streamline file operations. If you’re dealing with Excel files regularly, MiniExcel is worth adding to your toolkit!</p><p><a href="https://github.com/mini-software/MiniExcel">GitHub - mini-software/MiniExcel: Fast, Low-Memory, Easy Excel .NET helper to import/export/template spreadsheet (support Linux, Mac)</a></p><p>👏 Enjoyed the article? Hit follow to stay updated and show your support!</p><p>💬 Think I missed something? Drop your thoughts in the comments or reach out to me directly — I’d love to hear your feedback.</p><p>⬇️ Dive into my other articles for more insights and tips.</p><p>💬 Spot any errors or have additional ideas? Let me know in the comments — I appreciate every bit of input!</p><p>👥 Found this interesting? Share it with a friend and spark a discussion. Sometimes the best insights come from a good debate.</p><p>🚀 Keep pushing forward, stay inspired, and never stop learning.</p><p><strong>Thank you for reading!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c7ef5993bc0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/convert-between-csv-and-excel-files-2c7ef5993bc0">📑 How to easy Convert Between CSV and Excel Files</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Exceptions in .NET 8 Using IExceptionHandler]]></title>
            <link>https://medium.com/@valentin.osidach/handling-exceptions-in-net-8-c6d6a03c1c7f?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6d6a03c1c7f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 06:02:20 GMT</pubDate>
            <atom:updated>2024-09-11T06:02:20.228Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling Exceptions in .NET 8 Using IExceptionHandler</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OA1X5cYBxXH_6Vsguqg24Q.png" /></figure><h3>Step-by-Step Guide</h3><p>Exception handling is essential for building robust applications, and .NET 8 offers a streamlined way to handle exceptions globally using IExceptionHandler.</p><p>This approach allows you to define a centralized error-handling strategy that is easy to maintain and consistent across your application.</p><p>In this article, we will guide you through setting up IExceptionHandler step by step.</p><h3>Step 1: Set Up Your ASP.NET Core Project</h3><p>First, ensure you have an ASP.NET Core project set up. If you don’t have one yet, create a new project using the .NET CLI:</p><pre>dotnet new webapi -n ExceptionHandlingDemo</pre><h3>Step 2: Create a Global Exception Handler</h3><p>The global exception handler class will implement IExceptionHandler, where you define how exceptions are managed in your application.</p><ol><li><strong>Create the Exception Handler Class:</strong></li></ol><p>Create a new folder named Handlers in your project, then add a class called GlobalExceptionHandler.cs</p><pre>public class GlobalExceptionHandler : IExceptionHandler<br>{<br>    public async ValueTask&lt;bool&gt; TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)<br>    {<br>        var problemDetails = new ProblemDetails<br>        {<br>            Title = &quot;An error occurred&quot;,<br>            Status = StatusCodes.Status400BadRequest,<br>            Detail = exception.Message<br>        };<br><br>        httpContext.Response.StatusCode = problemDetails.Status.Value;<br><br>        await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);<br><br>        return true;<br>    }<br>}</pre><p><strong>HandleAsync(HttpContext context)</strong>: This method is responsible for handling the exception. It retrieves the exception from IExceptionHandlerFeature, logs it, and sends a structured JSON response to the client.</p><h3>Step 3: Register the Exception Handler in the Service Container</h3><p>Next, register your GlobalExceptionHandler in the service container using services.AddExceptionHandler&lt;GlobalExceptionHandler&gt;().</p><p><strong>Modify </strong><strong>Program.cs:</strong></p><p>Open Program.cs and register the global exception handler in the services configuration:</p><pre>using Microsoft.AspNetCore.Builder;<br>using Microsoft.Extensions.DependencyInjection;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddControllers();<br><br>// Register the global exception handler<br>builder.Services.AddExceptionHandler&lt;GlobalExceptionHandler&gt;();<br><br>var app = builder.Build();<br><br>// Use the global exception handler<br>app.UseExceptionHandler();<br><br>app.UseHttpsRedirection();<br>app.UseAuthorization();<br>app.MapControllers();<br><br>app.Run();</pre><p><strong>Explanation of Changes:</strong></p><ul><li><strong>services.AddExceptionHandler&lt;GlobalExceptionHandler&gt;()</strong>: Registers your custom exception handler in the service container, making it available for use.</li><li><strong>app.UseExceptionHandler()</strong>: Adds the middleware that utilizes your registered exception handler. This middleware catch</li></ul><h3><strong>Step 4: Test the Global Exception Handler</strong></h3><p>To test your exception handling setup, create a simple controller that throws an exception.</p><ol><li><strong>Create a Test Controller:</strong></li></ol><p>In the Controllers folder, add a new controller called TestController.cs:</p><pre>using Microsoft.AspNetCore.Mvc;<br><br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class TestController : ControllerBase<br>{<br>    [HttpGet(&quot;throw&quot;)]<br>    public IActionResult ThrowException()<br>    {<br>        throw new Exception(&quot;This is a test exception from controller.&quot;);<br>    }<br>}</pre><p><strong>2. Test the Endpoint:</strong></p><ul><li>Run your application (Press F5 or use the commanddotnet run) and navigate to https://localhost:5001/api/test/throw in your browser or use Postman or Swagger.</li><li>You should see the JSON response from the GlobalExceptionHandler, confirming that your global exception handling is working as expected.</li></ul><pre>{<br>  &quot;title&quot;: &quot;An error occurred&quot;,<br>  &quot;status&quot;: 400,<br>  &quot;detail&quot;: &quot;This is a test exception from controller.&quot;<br>}</pre><h3>Additional:</h3><p><strong>1. </strong>Exception Handler with a <strong>Logger</strong></p><pre>//Inject Logger using DI<br>public class GlobalExceptionHandler(ILogger&lt;GlobalExceptionHandler&gt; logger) : IExceptionHandler<br>{<br>    public async ValueTask&lt;bool&gt; TryHandleAsync(<br>      HttpContext httpContext, <br>      Exception exception, <br>      CancellationToken cancellationToken)<br>    {<br>        //Log exception<br>        logger.LogError(exception, &quot;An unhandled exception occurred.&quot;);<br><br>        var problemDetails = new ProblemDetails<br>        {<br>            Title = &quot;An error occurred&quot;,<br>            Status = StatusCodes.Status400BadRequest,<br>            Detail = exception.Message<br>        };<br><br>        httpContext.Response.StatusCode = problemDetails.Status.Value;<br><br>        await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);<br><br>        return true;<br>    }<br>}</pre><p><strong>2. </strong>Exception Handler for a specific Exception<strong> </strong>like <strong>DivideByZeroException</strong></p><pre>public class DivideByZeroExceptionHandler : IExceptionHandler<br>{<br>    public async ValueTask&lt;bool&gt; TryHandleAsync(<br>      HttpContext httpContext, <br>      Exception exception, <br>      CancellationToken cancellationToken)<br>    {<br>        // if exception is not DivideByZeroException then skip exception handling<br>        if(exception is not DivideByZeroException zeroException)<br>        {<br>            return true;<br>        }<br><br>        var problemDetails = new ProblemDetails<br>        {<br>            Title = &quot;An error occurred&quot;,<br>            Status = StatusCodes.Status400BadRequest,<br>            Detail = exception.Message<br>        };<br><br>        httpContext.Response.StatusCode = problemDetails.Status.Value;<br><br>        await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);<br><br>        return true;<br>    }<br>}</pre><p><strong>3. </strong>Exception Handler for the <strong>ValidationException </strong>with detailed information</p><pre>public class ValidationExceptionHandler : IExceptionHandler<br>{<br>    public async ValueTask&lt;bool&gt; TryHandleAsync(<br>            HttpContext httpContext, <br>            Exception exception,<br>            CancellationToken cancellationToken)<br>    {<br>        if (exception is not ValidationException validationException)<br>        {<br>            return true;<br>        }<br><br>        var problemDetails = new ProblemDetails<br>        {<br>            Title = &quot;An error occurred&quot;,<br>            Status = StatusCodes.Status400BadRequest,<br>            Detail = &quot;One or more validation errors occurred.&quot;,<br>            Type = exception.GetType().Name,<br>            Instance = $&quot;{httpContext.Request.Method} {httpContext.Request.Path}&quot;,<br>            Extensions = { [&quot;errors&quot;] = validationException.Errors }<br>        };<br><br>        httpContext.Response.StatusCode = problemDetails.Status.Value;<br><br>        await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);<br><br>        return true;<br>    }<br>}</pre><pre>{<br>  &quot;type&quot;: &quot;ValidationException&quot;,<br>  &quot;title&quot;: &quot;An error occurred&quot;,<br>  &quot;status&quot;: 400,<br>  &quot;detail&quot;: &quot;One or more validation errors occurred.&quot;,<br>  &quot;instance&quot;: &quot;POST /api/Auth&quot;,<br>  &quot;errors&quot;: [<br>    {<br>      &quot;propertyName&quot;: &quot;Password&quot;,<br>      &quot;errorMessage&quot;: &quot;&#39;Password&#39; can not be null.&quot;,<br>      &quot;attemptedValue&quot;: null,<br>      &quot;customState&quot;: null,<br>      &quot;severity&quot;: 0,<br>      &quot;errorCode&quot;: &quot;NotEmptyValidator&quot;,<br>      &quot;formattedMessagePlaceholderValues&quot;: {<br>        &quot;PropertyName&quot;: &quot;Password&quot;,<br>        &quot;PropertyValue&quot;: null<br>      }<br>    }<br>  ]<br>}</pre><p><a href="https://medium.com/@valentin.osidach/list/aeeed1ecd4c8">Most popular C# articles</a></p><h3>Conclusion</h3><p>Using IExceptionHandler in .NET 8 allows you to centralize exception handling in your application. This approach not only simplifies error management but also ensures consistent responses across your entire application, improving the overall robustness and maintainability of your code.</p><p>By following these steps, you can quickly set up an effective global exception handler that captures and manages errors gracefully, ensuring your application remains resilient even when things go wrong.</p><p>👏 Enjoyed the article? Hit follow to stay updated and show your support!</p><p>💬 Think I missed something? Drop your thoughts in the comments or reach out to me directly — I’d love to hear your feedback.</p><p>⬇️ Dive into my other articles for more insights and tips.</p><p>💬 Spot any errors or have additional ideas? Let me know in the comments — I appreciate every bit of input!</p><p>👥 Found this interesting? Share it with a friend and spark a discussion. Sometimes the best insights come from a good debate.</p><p>🚀 Keep pushing forward, stay inspired, and never stop learning.</p><p><strong>Thank you for reading!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6d6a03c1c7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating your own project on RapidAPI using .Net 8 and c#]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/c-sharp-programming/creating-your-own-project-on-rapidapi-using-net-8-and-c-0c1d0170b104?source=rss-40144240e6f4------2"><img src="https://cdn-images-1.medium.com/max/1920/1*yt7VRx3SQL_P1PVgfm5SOQ.png" width="1920"></a></p><p class="medium-feed-snippet">Introduction how to create your own project on RapidAPI using&#xA0;.Net 8 and c#</p><p class="medium-feed-link"><a href="https://medium.com/c-sharp-programming/creating-your-own-project-on-rapidapi-using-net-8-and-c-0c1d0170b104?source=rss-40144240e6f4------2">Continue reading on Any Programming »</a></p></div>]]></description>
            <link>https://medium.com/c-sharp-programming/creating-your-own-project-on-rapidapi-using-net-8-and-c-0c1d0170b104?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c1d0170b104</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 06:01:35 GMT</pubDate>
            <atom:updated>2024-09-12T21:21:13.670Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Guide how to Saving Files in an Archive Using C# .Net]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/c-sharp-programming/guide-how-to-saving-files-in-an-archive-using-c-net-19286d087286?source=rss-40144240e6f4------2"><img src="https://cdn-images-1.medium.com/max/1920/1*LJNVO_VmTWfWsK6OkfFE6g.png" width="1920"></a></p><p class="medium-feed-snippet">Guide to Saving Files in an Archive Using C# and System.IO.Compression</p><p class="medium-feed-link"><a href="https://medium.com/c-sharp-programming/guide-how-to-saving-files-in-an-archive-using-c-net-19286d087286?source=rss-40144240e6f4------2">Continue reading on Any Programming »</a></p></div>]]></description>
            <link>https://medium.com/c-sharp-programming/guide-how-to-saving-files-in-an-archive-using-c-net-19286d087286?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/19286d087286</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 20:08:50 GMT</pubDate>
            <atom:updated>2024-09-03T20:08:50.700Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[MiniExcel in Examples C# .Net 8]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/c-sharp-programming/miniexcel-in-examples-c-net-8-aa052f01e12d?source=rss-40144240e6f4------2"><img src="https://cdn-images-1.medium.com/max/1920/1*i05Lld9r5JjvZv9_vu1FyA.png" width="1920"></a></p><p class="medium-feed-snippet">Simple examples with read and write excel files</p><p class="medium-feed-link"><a href="https://medium.com/c-sharp-programming/miniexcel-in-examples-c-net-8-aa052f01e12d?source=rss-40144240e6f4------2">Continue reading on Any Programming »</a></p></div>]]></description>
            <link>https://medium.com/c-sharp-programming/miniexcel-in-examples-c-net-8-aa052f01e12d?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa052f01e12d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 06:01:52 GMT</pubDate>
            <atom:updated>2024-09-07T11:08:51.255Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The best dynamic LINQ library with Gridify in .NET]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/c-sharp-programming/the-best-dynamic-linq-library-with-gridify-in-net-ac3cb875b5b0?source=rss-40144240e6f4------2"><img src="https://cdn-images-1.medium.com/max/1920/1*faVhjillIvoKEh87YvOKTQ.png" width="1920"></a></p><p class="medium-feed-snippet">Introduction to Gridify with Examples</p><p class="medium-feed-link"><a href="https://medium.com/c-sharp-programming/the-best-dynamic-linq-library-with-gridify-in-net-ac3cb875b5b0?source=rss-40144240e6f4------2">Continue reading on Any Programming »</a></p></div>]]></description>
            <link>https://medium.com/c-sharp-programming/the-best-dynamic-linq-library-with-gridify-in-net-ac3cb875b5b0?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac3cb875b5b0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linq]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 06:01:46 GMT</pubDate>
            <atom:updated>2024-09-11T02:52:36.626Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding BackgroundTasks in .Net 8 C#]]></title>
            <link>https://medium.com/c-sharp-programming/understanding-backgroundtasks-in-net-8-c-19bedb56fc7b?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/19bedb56fc7b</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 06:01:55 GMT</pubDate>
            <atom:updated>2024-09-10T09:41:10.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding BackgroundTasks in .Net 8 C#</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MT0hbNhT4nCPXQ9SaaLv_A.png" /></figure><h3>Understanding BackgroundTasks</h3><p>Background tasks in .NET are typically used for operations that need to run without blocking the main thread, ensuring the application remains responsive. In .NET 8, the infrastructure for handling background tasks has been refined to provide better performance, resource management, and simplicity in implementation.</p><h3>Setting Up a Background Task</h3><p>You generally use the interface to create a background task in .NET 8. This interface provides a straightforward way to manage long-running tasks that start when the application starts and stop when the application stops.</p><pre>using System;<br>using System.Threading;<br>using System.Threading.Tasks;<br>using Microsoft.Extensions.Hosting;<br>using Microsoft.Extensions.Logging;<br><br>public class MyBackgroundService : BackgroundService<br>{<br>    private readonly ILogger&lt;MyBackgroundService&gt; _logger;<br><br>    public MyBackgroundService(ILogger&lt;MyBackgroundService&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br><br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        _logger.LogInformation(&quot;Background task starting.&quot;);<br><br>        while (!stoppingToken.IsCancellationRequested)<br>        {<br>            _logger.LogInformation(&quot;Background task doing work.&quot;);<br>            //Your code here ...<br>            await Task.Delay(1000, stoppingToken); <br>        }<br><br>        _logger.LogInformation(&quot;Background task stopping.&quot;);<br>    }<br>}</pre><p>In this example:</p><ul><li><strong>MyBackgroundService</strong> inherits from BackgroundService, a base class provided by .NET for implementing background tasks.</li><li>The <strong>ExecuteAsync</strong> method is where the background work is performed. It runs in a loop until the application is stopped or a cancellation token is triggered.</li><li>The <strong>Task.Delay(1000)</strong> simulates a task running every second.</li></ul><p><a href="https://medium.com/@valentin.osidach/using-hangfire-background-jobs-in-net-8-95c0ac30c1ec">Using Hangfire Background Jobs in .NET 8</a></p><h4>Registering the Background Service</h4><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddHostedService&lt;MyBackgroundService&gt;();</pre><h4>Advanced Scenarios with BackgroundTasks</h4><ul><li><strong>Scoped Services</strong>: If your background task needs to interact with services registered with a scoped lifetime, you can create a scope inside your task.</li><li><strong>Periodic Tasks</strong>: You can leverage timers or scheduling libraries for tasks that need to run at regular intervals.</li><li><strong>Concurrency</strong>: If your task involves parallel operations, ensure proper concurrency management to avoid issues like race conditions.</li></ul><h3>Background Task with <strong>Scoped Services</strong></h3><pre>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br>using Microsoft.Extensions.Logging;<br>using System;<br>using System.Threading;<br>using System.Threading.Tasks;<br><br>public class ScopedBackgroundService : BackgroundService<br>{<br>    private readonly IServiceProvider _serviceProvider;<br>    private readonly ILogger&lt;ScopedBackgroundService&gt; _logger;<br><br>    public ScopedBackgroundService(IServiceProvider serviceProvider, ILogger&lt;ScopedBackgroundService&gt; logger)<br>    {<br>        _serviceProvider = serviceProvider;<br>        _logger = logger;<br>    }<br><br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        _logger.LogInformation(&quot;Scoped Background Service is starting.&quot;);<br><br>        while (!stoppingToken.IsCancellationRequested)<br>        {<br>            _logger.LogInformation(&quot;Scoped Background Service is doing background work.&quot;);<br><br>            // Create a new scope<br>            using (var scope = _serviceProvider.CreateScope())<br>            {<br>                //Your service<br>                var scopedProcessingService = scope.ServiceProvider.GetRequiredService&lt;IScopedProcessingService&gt;();<br><br>                await scopedProcessingService.DoWork(stoppingToken);<br>            }<br><br>            await Task.Delay(5000, stoppingToken); // Simulate some delay between work cycles<br>        }<br><br>        _logger.LogInformation(&quot;Scoped Background Service is stopping.&quot;);<br>    }<br>}</pre><h4>Registering the Background Service</h4><pre>var builder = WebApplication.CreateBuilder(args);<br>var services = builder.Services;<br><br>services.AddHostedService&lt;MyBackgroundService&gt;();<br>services.AddScoped&lt;IScopedProcessingService, ScopedProcessingService&gt;();</pre><h3>Explanation of the Implementation</h3><ul><li><strong>Scoped Service</strong>: ScopedProcessingService is a service with a scoped lifetime, meaning its instance is tied to the lifespan of a specific request or operation.</li><li><strong>Background Service</strong>: ScopedBackgroundService inherits from BackgroundService and is designed to run continuously while the application is running.</li><li><strong>Creating a Scope</strong>: Inside the ExecuteAsync method of the background service, a new scope is created using _serviceProvider.CreateScope(). This scope allows the background service to resolve and use the ScopedProcessingService.</li><li><strong>Task Execution</strong>: The scoped service (ScopedProcessingService) performs its work inside this scope, ensuring that all dependencies with scoped lifetimes are disposed of properly when the scope ends.</li></ul><ul><li><a href="https://medium.com/@valentin.osidach/understanding-genericrepository-in-c-and-net-8-b44db3b0b7db">Understanding GenericRepository in C# and .NET 8</a></li><li><a href="https://medium.com/@valentin.osidach/create-your-own-nuget-package-4f1b99355e72">Create your own Nuget package</a></li><li><a href="https://medium.com/@valentin.osidach/create-free-qr-codes-easily-with-c-programming-with-zxing-net-bde5f716215c">Create Free QR Codes Easily with C# programming with ZXing.NET</a></li></ul><h3>Conclusion</h3><p>Background tasks are a powerful feature in .NET 8, enabling developers to offload time-consuming or repetitive tasks from the main application thread. With proper implementation, these tasks can enhance the responsiveness and scalability of your applications. By following best practices around registration, graceful shutdowns, and monitoring, you can ensure that your background tasks are reliable and performant.</p><p>Whether you’re building a web application, an API, or a microservice, leveraging background tasks can be a game-changer in handling asynchronous operations efficiently.</p><p><a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-8.0&amp;tabs=visual-studio">Microsoft Learn Background tasks</a></p><p><a href="https://medium.com/@valentin.osidach/the-best-way-to-work-with-exel-in-net-is-miniexcel-0a113f70e5aa">The best way to work with Exel in .NET is MiniExcel?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19bedb56fc7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/understanding-backgroundtasks-in-net-8-c-19bedb56fc7b">Understanding BackgroundTasks in .Net 8 C#</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building High-Performance .NET Core Web APIs with FastEndpoints]]></title>
            <link>https://medium.com/c-sharp-programming/building-high-performance-net-core-web-apis-with-fastendpoints-0f0d82e95d55?source=rss-40144240e6f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f0d82e95d55</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Valentyn Osidach ]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 06:03:21 GMT</pubDate>
            <atom:updated>2024-09-09T17:40:56.120Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building High-Performance .NET Core Web APIs with FastEndpoints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXPfxsKrgi0cyWolOGU9aA.png" /></figure><h3>Introduction</h3><p>Performance is key for any developer or organization in this fast-moving scenery of web development. At the core of modern applications are APIs, whose demand is greater than ever for speedy and reliable responses. FastEndpoints is a lightweight framework designed to ease and speed up the development of High-Performance .NET Core Web APIs.</p><p>The following article will describe what FastEndpoints is, why it is an interesting choice for building APIs, and how to get started with this package in your .NET Core projects.</p><h3>What is FastEndpoints?</h3><p><strong>FastEndpoints</strong> is a minimalist framework built on top of ASP.NET Core, offering a streamlined approach to building Web APIs. It aims to reduce boilerplate code and enhance performance, making it easier and quicker to develop APIs without sacrificing flexibility or power.</p><p>FastEndpoints introduces a different approach to handling API requests compared to traditional controllers in ASP.NET Core. It leverages the concept of <strong>endpoints</strong>, which are specialized classes that encapsulate the request-handling logic, including validation, authentication, and response generation.</p><h3>Why Use FastEndpoints?</h3><p>FastEndpoints offers several benefits that make it an attractive choice for building .NET Core Web APIs:</p><ol><li><strong>Simplicity</strong>: FastEndpoints promotes a clear and concise structure for your API logic, reducing the need for boilerplate code and unnecessary abstractions.</li><li><strong>Performance</strong>: With a focus on minimizing overhead, FastEndpoints is designed to deliver high-performance APIs that can handle a large number of requests efficiently.</li><li><strong>Modularity</strong>: FastEndpoints encourages modular design, making it easy to organize and maintain your codebase. Each endpoint is self-contained, leading to better separation of concerns.</li><li><strong>Built-in Features</strong>: FastEndpoints comes with built-in support for common API requirements, such as request validation, authentication, and error handling, allowing you to focus on business logic.</li></ol><ul><li><a href="https://medium.com/@valentin.osidach/using-hangfire-background-jobs-in-net-8-95c0ac30c1ec">Using Hangfire Background Jobs in .NET 8</a></li><li><a href="https://medium.com/@valentin.osidach/understanding-genericrepository-in-c-and-net-8-b44db3b0b7db">Understanding GenericRepository in C# and .NET 8</a></li></ul><h3>Getting Started with FastEndpoints</h3><p>Let’s walk through the process of setting up a .NET Core Web API project using FastEndpoints.</p><h4>1. Setting Up the Project</h4><p>First, you need to create a new ASP.NET Core Web API project. You can do this using the .NET CLI:</p><pre>dotnet new webapi -n FastEndpointsDemo</pre><h4>2. Next, install the FastEndpoints NuGet package</h4><pre>dotnet add package FastEndpoints</pre><h4>3. Define Your First Endpoint</h4><p>With FastEndpoints, you define API endpoints as classes that inherit from the Endpoint class. Let&#39;s create a simple example where we define an endpoint to handle HTTP GET requests for fetching a list of products.</p><p>Create a new folder called Endpoints, and inside it, create a file named GetProductsEndpoint.cs:</p><pre>using FastEndpoints;<br><br>public class GetProductsEndpoint : EndpointWithoutRequest&lt;List&lt;Product&gt;&gt;<br>{<br>    public override void Configure()<br>    {<br>        Verbs(Http.GET);<br>        Routes(&quot;/products&quot;);<br>        AllowAnonymous();<br>    }<br><br>    public override async Task HandleAsync(CancellationToken ct)<br>    {<br>        var products = new List&lt;Product&gt;<br>        {<br>            new Product { Id = 1, Name = &quot;Laptop&quot;, Price = 1200.99M },<br>            new Product { Id = 2, Name = &quot;Smartphone&quot;, Price = 699.99M }<br>        };<br><br>        await SendAsync(products);<br>    }<br>}<br><br>public class Product<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br>}</pre><p>In this example:</p><ul><li><strong>EndpointWithoutRequest&lt;List&lt;Product&gt;&gt;</strong> indicates that this endpoint doesn’t expect a request body but will return a list of Product objects.</li><li>The Configure method is used to specify the HTTP verb, route, and other settings.</li><li>The HandleAsync method contains the logic for handling the request and sending the response.</li></ul><h4>4. Register FastEndpoints</h4><p>To use FastEndpoints, you need to register it in your Program.cs file.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Register FastEndpoints<br>builder.Services.AddFastEndpoints();<br><br>var app = builder.Build();<br><br>// Use FastEndpoints<br>app.UseFastEndpoints();<br><br>app.Run();</pre><ul><li><a href="https://medium.com/@valentin.osidach/create-your-own-nuget-package-4f1b99355e72">Create your own Nuget package</a></li><li><a href="https://medium.com/@valentin.osidach/create-your-own-nuget-package-4f1b99355e72">Create your own Nuget package</a></li><li><a href="https://medium.com/@valentin.osidach/create-free-qr-codes-easily-with-c-programming-with-zxing-net-bde5f716215c">Create Free QR Codes Easily with C# programming with ZXing.NET</a></li></ul><h3>Advanced Features</h3><p>FastEndpoints offers a range of features that allow you to build more complex APIs efficiently:</p><ul><li><strong>Request Validation</strong>: FastEndpoints allows you to easily add validation logic to your endpoints. You can define validation rules using FluentValidation or custom logic.</li><li><strong>Authentication &amp; Authorization</strong>: FastEndpoints integrates seamlessly with ASP.NET Core’s authentication and authorization mechanisms, allowing you to secure your APIs with minimal configuration.</li><li><strong>Middleware</strong>: You can add custom middleware to your endpoints, providing a powerful way to inject additional logic into the request pipeline.</li><li><strong>Error Handling</strong>: FastEndpoints simplifies error handling by providing built-in mechanisms to handle exceptions and return standardized error responses.</li></ul><h3>Conclusion</h3><p>FastEndpoints is a powerful tool for building high-performance, modular, and easy-to-maintain Web APIs in .NET Core. By reducing boilerplate code and offering a clean, concise approach to defining endpoints, it allows developers to focus on writing business logic rather than dealing with repetitive infrastructure concerns.</p><p>Whether you are building a small microservice or a large-scale API, FastEndpoints can help you streamline your development process while ensuring that your APIs are fast and reliable. If you’re looking to speed up your .NET Core API development while maintaining high performance, FastEndpoints is definitely worth exploring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f0d82e95d55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/building-high-performance-net-core-web-apis-with-fastendpoints-0f0d82e95d55">Building High-Performance .NET Core Web APIs with FastEndpoints</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>