<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tips - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/tips/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Mon, 23 Nov 2026 17:53:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>Tips - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Unit Test and Mock Automapper ASP.NET Core</title>
		<link>https://thecodebuzz.com/unit-test-mock-automapper-asp-net-core-imapper/</link>
					<comments>https://thecodebuzz.com/unit-test-mock-automapper-asp-net-core-imapper/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 04 Aug 2022 01:29:00 +0000</pubDate>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[asp net core testing]]></category>
		<category><![CDATA[asp net core unit testing]]></category>
		<category><![CDATA[automapper mock list]]></category>
		<category><![CDATA[automapper resolutioncontext unit test]]></category>
		<category><![CDATA[automapper unit test .net core]]></category>
		<category><![CDATA[automapper unit test assertconfigurationisvalid]]></category>
		<category><![CDATA[automapper xunit]]></category>
		<category><![CDATA[how to mock automapper projectto]]></category>
		<category><![CDATA[initialize automapper in unit test]]></category>
		<category><![CDATA[mapper not initialized unit test]]></category>
		<category><![CDATA[mock automapper unit test c#]]></category>
		<category><![CDATA[mock mapper c#]]></category>
		<category><![CDATA[xunit automapper]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=12716</guid>

					<description><![CDATA[<p>Unit Test and Mock Automapper ASP.NET Core Today in this article we will see how to write Unit Test and Mock Automapper in ASP.NET Core application. As we learned in our last article on Automapper, it was very easy to configure Automapper in the API pipeline using the Dependency Injection (DI) principle. Although I found [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/unit-test-mock-automapper-asp-net-core-imapper/">Unit Test and Mock Automapper ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Unit Test and Mock Automapper ASP.NET Core</h1>



<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/10/Automapper-mocking-and-unit-testing-IMapper.jpg" alt="" class="wp-image-12725" width="502" height="316" srcset="https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-mocking-and-unit-testing-IMapper.jpg 685w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-mocking-and-unit-testing-IMapper-300x189.jpg 300w" sizes="(max-width: 502px) 100vw, 502px" /></figure>



<p class="wp-block-paragraph">Today in this article we will see how to write Unit Test and Mock Automapper in ASP.NET Core application.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">As we learned in our <a href="https://www.thecodebuzz.com/configure-automapper-asp-net-core-profile-map-object/" target="_blank" rel="noreferrer noopener" title="Configure Automapper in ASP.NET Core – Getting Started">last </a>article on Automapper, it was very easy to configure Automapper in the API pipeline using the <strong>Dependency Injection (DI)</strong> principle.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Although I found the <em><strong>IMapper </strong></em>interface does provide DI and allows us to program by Abstraction but still requires us to Initialize the Mapping configuration at startup.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Due to the same reason, <strong><em>IMapper </em></strong>can not be completely mocked by setting up a mock extension method in a<strong><em> </em></strong>regular way.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">But we can very much use a declarative auto-mapper profile and inject it into our module.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Today in this article, we will cover below aspects,</p>



<p class="wp-block-paragraph"></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-testinitialize-or-test-method-initilize">Test Initialize Mapping Profile</a></li><li><a href="#aioseo-test-initialize-mapping-profile">Injecting Mapper profile in Test method</a></li></ul></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Today I will talk about simple techniques to overcome this issue in this article.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Let&#8217;s first look at the<strong> SUT </strong>i.e. Software under test example.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>Original Method </strong>where Automapper is used,</p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/10/Automapper-DI-Constructor-injection-IMapper-in-Controller-1-1024x341.jpg" alt="" class="wp-image-12719" width="466" height="155" srcset="https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-DI-Constructor-injection-IMapper-in-Controller-1-1024x341.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-DI-Constructor-injection-IMapper-in-Controller-1-300x100.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-DI-Constructor-injection-IMapper-in-Controller-1-768x256.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-DI-Constructor-injection-IMapper-in-Controller-1-1536x511.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-DI-Constructor-injection-IMapper-in-Controller-1-2048x681.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-DI-Constructor-injection-IMapper-in-Controller-1-785x261.jpg 785w" sizes="(max-width: 466px) 100vw, 466px" /></figure>



<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-Imapper-using-Xunit.jpg" alt="Unit Test and Mock Automapper" class="wp-image-12718" width="466" height="260" srcset="https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-Imapper-using-Xunit.jpg 776w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-Imapper-using-Xunit-300x167.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-Imapper-using-Xunit-768x429.jpg 768w" sizes="(max-width: 466px) 100vw, 466px" /></figure>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please visit the below article for the complete code,</p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/configure-automapper-asp-net-core-profile-map-object/" target="_blank" rel="noreferrer noopener" title="Configure Automapper in ASP.NET Core – Getting Started"><strong><em>Configure Automapper in ASP.NET Core – Getting Started</em></strong></a></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Below is how the profile is defined,</p>



<p class="wp-block-paragraph"></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
public class SourceMappingProfile : Profile
    {
        public SourceMappingProfile()
        {
            CreateMap&lt;Source, Destination&gt;()
                .ForMember(dest =&gt; dest.Name, o =&gt; o.MapFrom(src =&gt; src.FirstName))
                .ForMember(dest =&gt; dest.Identity, o =&gt; o.MapFrom(src =&gt; src.Id))
                .ForMember(dest =&gt; dest.Location, o =&gt; o.MapFrom(src =&gt; src.Address));
        }


    }
</pre></div>


<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">The test project does not have an inbuilt IoC hence we will have to initialize the <strong><em>Automapper </em></strong>configuration manually i.e. by instance invocation.</p>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading" id="aioseo-testinitialize-or-test-method-initilize">Test Initialize Mapping Profile</h3>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here in the XUnit Test class, the <strong><em>constructor </em></strong>of TestClass gets <a href="https://www.thecodebuzz.com/?p=22705">called before the execution of any Test method</a>. (which is equivalent to <strong><em>TestInitialize </em></strong>in MS Test terminology.)</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here we will instantiate the Automapper interface i.e. <em><strong>IMapper </strong></em>as Singleton so that the same instance will be used as-is for all Test methods.</p>



<p class="wp-block-paragraph"></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
    public class AutomapperASPNETCoreTests
    {
        private static IMapper _mapper;

        public AutomapperASPNETCoreTests()
        {
            if (_mapper == null)
            {
                var mappingConfig = new MapperConfiguration(mc =&gt;
                {
                    mc.AddProfile(new SourceMappingProfile());
                });
                IMapper mapper = mappingConfig.CreateMapper();
                _mapper = mapper;
            }
        }

        &#x5B;Fact]
        public void AutomapperASPNETCoreTest_Get_Valid_Mock_Automapper()
        {  
..
..
..

</pre></div>


<h2 class="wp-block-heading" id="aioseo-test-initialize-mapping-profile">Injecting Mapper profile in Test method</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here below is the implementation of TestMethod <em><strong>AutomapperASPNETCoreTest_Get_Valid_Mock_Automapper</strong></em>. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">This method when gets executed will initialize the <strong>IMapper </strong>instance with the given configuration and profile. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">All the test methods will use the same instance when for one execution to simplify test method executions. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Below is the final implementation of the <strong><em>Test </em></strong>method,</p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="453" src="https://www.thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-interface-IMapper-using-Xunit-initilaize-profile-1024x453.jpg" alt="Unit Test and Mock Automapper, xunit Automapper" class="wp-image-12720" srcset="https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-interface-IMapper-using-Xunit-initilaize-profile-1024x453.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-interface-IMapper-using-Xunit-initilaize-profile-300x133.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-interface-IMapper-using-Xunit-initilaize-profile-768x340.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-interface-IMapper-using-Xunit-initilaize-profile-785x347.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/10/Automapper-unit-test-and-mock-interface-IMapper-using-Xunit-initilaize-profile.jpg 1253w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">The above method uses the <em><strong>IMapper </strong></em>instance as defined in the Constructor of Test class.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong><em>References</em></strong>:</p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/configure-automapper-asp-net-core-profile-map-object/" target="_blank" rel="noreferrer noopener" title="Configure Automapper in ASP.NET Core – Getting Started"><strong><em>Configure Automapper in ASP.NET Core – Getting Started</em></strong></a></li>
</ul>



<ul class="wp-block-list">
<li><strong><em><a href="https://www.thecodebuzz.com/tdd-unit-testing-naming-conventions-and-standards/" target="_blank" rel="noreferrer noopener">How to Name Unit Test cases &#8211; Best Practices</a></em></strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph" style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size wp-block-paragraph"></p>



<p class="wp-block-paragraph" style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size wp-block-paragraph"></p>



<p class="has-medium-font-size wp-block-paragraph"><strong>Happy Coding </strong>!!</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<hr>



<p class="wp-block-paragraph"></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p><p>The post <a href="https://thecodebuzz.com/unit-test-mock-automapper-asp-net-core-imapper/">Unit Test and Mock Automapper ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/unit-test-mock-automapper-asp-net-core-imapper/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>CsvHelper in C#: Read and Write CSV Files in .NET</title>
		<link>https://thecodebuzz.com/csvhelper-read-csv-files-in-csharp-net-core/</link>
					<comments>https://thecodebuzz.com/csvhelper-read-csv-files-in-csharp-net-core/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 25 Jul 2022 02:44:00 +0000</pubDate>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[c# csv reader example]]></category>
		<category><![CDATA[csvhelper c#]]></category>
		<category><![CDATA[csvhelper datetime format]]></category>
		<category><![CDATA[csvhelper example]]></category>
		<category><![CDATA[csvhelper github]]></category>
		<category><![CDATA[csvhelper read line by line]]></category>
		<category><![CDATA[csvhelper read string]]></category>
		<category><![CDATA[csvhelper writeheader]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=23159</guid>

					<description><![CDATA[<p>Read CSV files in C# with CsvHelper: map rows to classes with ClassMap, handle headers, culture, missing and bad data, stream async, and write CSV.</p>
<p>The post <a href="https://thecodebuzz.com/csvhelper-read-csv-files-in-csharp-net-core/">CsvHelper in C#: Read and Write CSV Files in .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph">Your app receives a CSV file from a partner or an export, and you need the rows as C# objects: numbers as numbers, dates as dates, and no crash on the one broken line in row 40,000. A <code>string.Split(',')</code> loop breaks the first time a name contains a comma in quotes.</p>



<p class="wp-block-paragraph"><strong>CsvHelper</strong> (<a href="https://joshclose.github.io/CsvHelper/" target="_blank" rel="noopener">official docs</a>) is the usual answer to <strong>read a CSV file in C#</strong>. It handles quotes, headers, culture and type conversion for you. The code below was built and run on .NET 10 with CsvHelper 33.1.0, and the section on the new API was run with CsvHelper 34.1.0. Nothing here needs a web server.</p>



<p class="wp-block-paragraph">This is the flow the article builds: read rows, map them to a class, and report bad rows instead of failing the whole file.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/csvhelper-read-csv-flow.gif" alt="Animation of CsvHelper reading a CSV file into a list of Employee objects, reporting one bad row with a non-numeric Id and skipping it"/></figure>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#which-approach">Which approach should you choose?</a></li><li><a href="#aioseo-install-nuget-package">Prerequisites</a></li><li><a href="#sample">Step 1: Create a sample CSV file</a></li><li><a href="#aioseo-csv-to-objects-conversion">Step 2: Read a CSV file into a class</a></li><li><a href="#classmap">Step 3: ClassMap, headers and culture</a></li><li><a href="#bad-data">Step 4: Missing fields and bad data</a></li><li><a href="#dynamic">Dynamic, records and reading field by field</a></li><li><a href="#async">Read a large CSV file asynchronously</a></li><li><a href="#write">Write a CSV file</a></li><li><a href="#v34">CsvHelper 34: the new API</a></li><li><a href="#result">What the output looks like</a></li><li><a href="#troubleshooting">Common problems and fixes</a></li><li><a href="#faq">Frequently asked questions</a></li><li><a href="#summary">Summary</a></li></ul></div>



<span id="aioseo-getting-started"></span>



<h2 class="wp-block-heading" id="which-approach">Which approach should you choose?</h2>



<ul class="wp-block-list">
<li><strong>CsvHelper 33.1.0</strong>: the long-standing API (<code>CsvConfiguration</code>, <code>ClassMap</code>, culture argument). Almost every existing tutorial, Stack Overflow answer and code base uses it, so pick it when you maintain existing code or want the most examples.</li>

<li><strong>CsvHelper 34.x</strong>: a rewrite released in 2026 with a different API (source-generated <code>[CsvRecord]</code> types, <code>CsvReaderOptions</code>, no <code>ClassMap</code>). Pick it for new code on .NET 8 or later. See the section below and the <a href="https://joshclose.github.io/CsvHelper/migration/v34.0.0.html" target="_blank" rel="noopener">migration guide</a>.</li>

<li>Need a comparison with <code>StreamReader</code> or <code>TextFieldParser</code> and no package? See <a href="https://www.thecodebuzz.com/read-csv-file-in-net-core/">Read a CSV file in .NET Core</a> and <a href="https://www.thecodebuzz.com/read-csv-file-in-net-core-textfieldparser/">Read a CSV file using TextFieldParser</a>. This article only covers CsvHelper.</li>
</ul>



<p class="wp-block-paragraph">The main sections use the 33.1.0 API. Pin the version in your project file so an upgrade does not break the build:</p>



<h2 class="wp-block-heading" id="aioseo-install-nuget-package">Prerequisites</h2>



<ul class="wp-block-list">
<li>A .NET 8, 9 or 10 project (a console app is enough).</li>

<li>The CsvHelper package, pinned to the API you follow.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
dotnet add package CsvHelper --version 33.1.0
</pre></div>


<h2 class="wp-block-heading" id="sample">Step 1: Create a sample CSV file</h2>



<p class="wp-block-paragraph">One name contains a comma (quoted), and one salary is empty. Those are the cases that break hand-written parsers.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
File.WriteAllText(&quot;employees.csv&quot;,
&quot;Id,Name,Salary,JoinDate\n1,Asha,5200.50,2022-03-14\n2,Ravi,,2021-11-01\n3,\&quot;Smith, John\&quot;,4800,2020-07-30\n&quot;);
</pre></div>


<h2 class="wp-block-heading" id="aioseo-csv-to-objects-conversion">Step 2: Read a CSV file into a class</h2>



<p class="wp-block-paragraph"><code>CsvReader</code> needs a <code>TextReader</code> and a culture. <code>GetRecords&lt;T&gt;()</code> matches header names to property names and converts each value. Use a nullable type such as <code>decimal?</code> for columns that can be empty.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;

using (var reader = new StreamReader(&quot;employees.csv&quot;))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    foreach (var e in csv.GetRecords&lt;Employee&gt;())
        Console.WriteLine($&quot;{e.Id} | {e.Name} | {e.Salary?.ToString() ?? &quot;null&quot;} | {e.JoinDate:yyyy-MM-dd}&quot;);
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; } = &quot;&quot;;
    public decimal? Salary { get; set; }
    public DateTime JoinDate { get; set; }
}
</pre></div>


<p class="wp-block-paragraph"><code>GetRecords</code> is lazy: it reads one row each time the loop moves, so call <code>.ToList()</code> only when you need everything in memory.</p>



<h2 class="wp-block-heading" id="classmap">Step 3: ClassMap, headers and culture</h2>



<p class="wp-block-paragraph"><strong>Culture</strong> decides how numbers and dates are parsed. Use <code>CultureInfo.InvariantCulture</code> for machine-generated files. If the file was exported in a European locale (<code>5200,50</code> with <code>;</code> as the separator), pass that culture and delimiter instead, or the value is read wrongly or throws.</p>



<p class="wp-block-paragraph"><strong>ClassMap</strong> is for when the header names do not match your property names, when you want defaults, or when you do not want attributes on the class. Register it on the reader context:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
File.WriteAllText(&quot;people.csv&quot;, &quot;emp_id;full_name;pay\n1;Asha;5200,50\n2;Ravi;4800,00\n&quot;);
var deConfig = new CsvConfiguration(new CultureInfo(&quot;de-DE&quot;)) { Delimiter = &quot;;&quot; };
using (var reader = new StreamReader(&quot;people.csv&quot;))
using (var csv = new CsvReader(reader, deConfig))
{
    csv.Context.RegisterClassMap&lt;EmployeeMap&gt;();
    foreach (var e in csv.GetRecords&lt;Employee&gt;())
        Console.WriteLine($&quot;{e.Id} | {e.Name} | {e.Salary}&quot;);
}

public sealed class EmployeeMap : ClassMap&lt;Employee&gt;
{
    public EmployeeMap()
    {
        Map(m =&gt; m.Id).Name(&quot;emp_id&quot;);
        Map(m =&gt; m.Name).Name(&quot;full_name&quot;);
        Map(m =&gt; m.Salary).Name(&quot;pay&quot;);
        Map(m =&gt; m.JoinDate).Optional().Default(new DateTime(2000, 1, 1));
    }
}
</pre></div>


<p class="wp-block-paragraph"><code>Optional()</code> lets a column be absent from the header, and <code>Default()</code> supplies the value then.</p>



<p class="wp-block-paragraph"><strong>No header row?</strong> Set <code>HasHeaderRecord = false</code> and map by position with <code>Index</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
File.WriteAllText(&quot;noheader.csv&quot;, &quot;1,Asha,5200.50\n2,Ravi,4800\n&quot;);
var noHeader = new CsvConfiguration(CultureInfo.InvariantCulture) { HasHeaderRecord = false };
using (var reader = new StreamReader(&quot;noheader.csv&quot;))
using (var csv = new CsvReader(reader, noHeader))
{
    csv.Context.RegisterClassMap&lt;IndexMap&gt;();
    foreach (var e in csv.GetRecords&lt;Employee&gt;())
        Console.WriteLine($&quot;{e.Id} | {e.Name} | {e.Salary}&quot;);
}

public sealed class IndexMap : ClassMap&lt;Employee&gt;
{
    public IndexMap()
    {
        Map(m =&gt; m.Id).Index(0);
        Map(m =&gt; m.Name).Index(1);
        Map(m =&gt; m.Salary).Index(2);
        Map(m =&gt; m.JoinDate).Ignore();
    }
}
</pre></div>


<h2 class="wp-block-heading" id="bad-data">Step 4: Missing fields and bad data</h2>



<p class="wp-block-paragraph">By default CsvHelper is strict. A header that does not match a property throws <code>HeaderValidationException</code>, a short row throws <code>MissingFieldException</code>, and a value that cannot be converted throws <code>TypeConverterException</code>. That is right for a file you control. For files from outside, decide per case what should happen. This file has a letter in an Id and a row with only two fields:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
File.WriteAllText(&quot;bad.csv&quot;, &quot;Id,Name,Salary,JoinDate\n1,Asha,5200,2022-03-14\nx,Ravi,4800,2021-11-01\n3,Neha\n4,Omar,3900,2020-01-05\n&quot;);
var errors = new List&lt;string&gt;();
var badConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    MissingFieldFound = null,   // short rows do not throw here
    HeaderValidated = null,     // header mismatch does not throw
    BadDataFound = args =&gt; errors.Add($&quot;bad data row {args.Context.Parser.Row}: {args.RawRecord.Trim()}&quot;),
    ReadingExceptionOccurred = args =&gt;
    {
        var row = args.Exception.Context?.Parser?.Row;
        errors.Add(args.Exception is TypeConverterException tc
            ? $&quot;row {row}: cannot convert &#039;{tc.Text}&#039; for {tc.MemberMapData.Member?.Name}&quot;
            : $&quot;row {row}: {args.Exception.Message.Split(&#039;\n&#039;)&#x5B;0]}&quot;);
        return false; // skip the row, keep reading
    }
};
using (var reader = new StreamReader(&quot;bad.csv&quot;))
using (var csv = new CsvReader(reader, badConfig))
{
    foreach (var e in csv.GetRecords&lt;Employee&gt;())
        Console.WriteLine($&quot;OK {e.Id} | {e.Name} | {e.Salary?.ToString() ?? &quot;null&quot;}&quot;);
}
errors.ForEach(x =&gt; Console.WriteLine(&quot;ERR &quot; + x));
</pre></div>


<p class="wp-block-paragraph">Rows 1 and 4 are returned, and the two broken rows are reported with their row number. Two things to know: <code>BadDataFound</code> is for malformed quoting, not for type errors, and a row that is missing a <em>required value type</em> (here <code>JoinDate</code> is a non-nullable <code>DateTime</code>) still fails conversion even with <code>MissingFieldFound = null</code>. Make the property nullable or give it a default if a short row should load.</p>



<span id="aioseo-csv-to-json-conversion"></span>



<h2 class="wp-block-heading" id="dynamic">Dynamic, records and reading field by field</h2>



<p class="wp-block-paragraph">If you do not want a class, <code>GetRecords&lt;dynamic&gt;()</code> returns objects whose properties are the header names. Every value is a string, so convert it yourself:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using (var reader = new StreamReader(&quot;employees.csv&quot;))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    foreach (var r in csv.GetRecords&lt;dynamic&gt;())
        Console.WriteLine($&quot;{r.Id} - {r.Name} - &#039;{r.Salary}&#039;&quot;);
}
</pre></div>


<p class="wp-block-paragraph">For full control, read the header and each row yourself and fetch fields by name:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using (var reader = new StreamReader(&quot;employees.csv&quot;))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    csv.Read(); csv.ReadHeader();
    while (csv.Read())
        Console.WriteLine($&quot;{csv.GetField&lt;int&gt;(&quot;Id&quot;)} {csv.GetField(&quot;Name&quot;)} {csv.GetField&lt;decimal?&gt;(&quot;Salary&quot;)}&quot;);
}
</pre></div>


<p class="wp-block-paragraph">C# positional records work too. With <code>public record EmployeeRec(int Id, string Name);</code>, CsvHelper fills the constructor from the matching columns and ignores the others (set <code>HeaderValidated = null</code> and <code>MissingFieldFound = null</code> in the configuration as shown in Step 4 if the file has extra or missing columns):</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using (var reader = new StreamReader(&quot;employees.csv&quot;))
using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture) { HeaderValidated = null, MissingFieldFound = null }))
{
    foreach (var r in csv.GetRecords&lt;EmployeeRec&gt;()) Console.WriteLine(r);
}

public record EmployeeRec(int Id, string Name);
</pre></div>


<h2 class="wp-block-heading" id="async">Read a large CSV file asynchronously</h2>



<p class="wp-block-paragraph"><code>GetRecordsAsync&lt;T&gt;()</code> returns an <code>IAsyncEnumerable&lt;T&gt;</code>. Rows are streamed, so a large file never sits in memory all at once, and the thread is free while the disk is read. This suits a web API or a background worker. For more on <code>await</code> in general, see <a href="https://www.thecodebuzz.com/async-await-csharp-net-guidelines-and-best-practices/">Async await best practices</a>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using (var reader = new StreamReader(&quot;employees.csv&quot;))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    await foreach (var e in csv.GetRecordsAsync&lt;Employee&gt;())
        Console.WriteLine($&quot;{e.Id} {e.Name}&quot;);
}
</pre></div>


<p class="wp-block-paragraph">In an upload endpoint, pass the request stream into the <code>StreamReader</code> instead of a file path. To send a file back to a client, see <a href="https://www.thecodebuzz.com/return-download-file-asp-net-core-webapi/">Return and download a file from an ASP.NET Core Web API</a>.</p>



<h2 class="wp-block-heading" id="write">Write a CSV file</h2>



<p class="wp-block-paragraph"><code>CsvWriter</code> quotes values that need it. Dates use the culture&#8217;s format unless you set one, so pick an explicit format for files other systems read:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
var list = new List&lt;Employee&gt; {
    new() { Id = 1, Name = &quot;Asha&quot;, Salary = 5200.5m, JoinDate = new DateTime(2022,3,14) },
    new() { Id = 2, Name = &quot;Smith, John&quot;, Salary = null, JoinDate = new DateTime(2020,7,30) } };
using (var writer = new StreamWriter(&quot;out.csv&quot;))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.Context.TypeConverterOptionsCache.GetOptions&lt;DateTime&gt;().Formats = new&#x5B;] { &quot;yyyy-MM-dd&quot; };
    await csv.WriteRecordsAsync(list);
}
</pre></div>


<h2 class="wp-block-heading" id="v34">CsvHelper 34: the new API</h2>



<p class="wp-block-paragraph">Version 34 (November 2026) is a rewrite for speed. Everything lives in the <code>CsvHelper</code> namespace, readers are created with factory methods, settings are <code>CsvReaderOptions</code>, and your class is marked <code>[CsvRecord]</code> and <code>partial</code> so a source generator writes the mapping at compile time. <code>ClassMap</code> and the culture argument are gone (invariant culture is the default; set <code>FormatProvider</code> otherwise). This ran with <code>dotnet add package CsvHelper --version 34.1.0</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using CsvHelper;

using (var reader = CsvReader.FromFile(&quot;employees.csv&quot;))
{
    foreach (var e in reader.GetRecords&lt;Employee&gt;())
        Console.WriteLine($&quot;{e.Id} | {e.Name} | {e.Salary?.ToString() ?? &quot;null&quot;} | {e.JoinDate:yyyy-MM-dd}&quot;);
}

// different header names, a European file, and an optional column
var options = new CsvReaderOptions { Separator = &#039;;&#039;, FormatProvider = new System.Globalization.CultureInfo(&quot;de-DE&quot;) };
using (var reader = CsvReader.FromFile(&quot;people.csv&quot;, options))
{
    foreach (var p in reader.GetRecords&lt;Person&gt;())
        Console.WriteLine($&quot;{p.Id} | {p.Name} | {p.Pay} | {p.Region}&quot;);
}

// no header: map by index
using (var reader = CsvReader.FromText(&quot;1,Asha,5200.50\n2,Ravi,4800\n&quot;, new CsvReaderOptions { HasHeader = false }))
{
    foreach (var a in reader.GetRecords&lt;Account&gt;())
        Console.WriteLine($&quot;{a.Id} | {a.Name} | {a.Balance}&quot;);
}

// bad data: report malformed quoting, skip records that do not convert
// use it with: CsvReader.FromText(text, messy) or CsvReader.FromFile(path, messy)
var messy = new CsvReaderOptions
{
    OnMalformedRecord = bad =&gt; Console.WriteLine($&quot;malformed record {bad.RecordNumber}: {bad.Reason}&quot;),
    OnRecordError = err =&gt; { Console.WriteLine($&quot;skipping record {err.RowNumber}: {err.Exception.Message}&quot;); return true; },
};

// async and writing (list is the List&lt;Employee&gt; from the writing section)
await using (var reader = CsvReader.FromFile(&quot;employees.csv&quot;))
{
    await foreach (var e in reader.GetRecordsAsync&lt;Employee&gt;()) Console.WriteLine($&quot;{e.Id} {e.Name}&quot;);
}
using (var writer = CsvWriter.ToFile(&quot;out.csv&quot;)) { writer.WriteRecords(list); }

&#x5B;CsvRecord]
public partial class Employee
{
    public int Id { get; set; }
    public string Name { get; set; } = &quot;&quot;;
    public decimal? Salary { get; set; }
    public DateTime JoinDate { get; set; }
}

&#x5B;CsvRecord]
public partial class Person
{
    &#x5B;CsvColumn(&quot;emp_id&quot;)] public int Id { get; set; }
    &#x5B;CsvColumn(&quot;full_name&quot;)] public string Name { get; set; } = &quot;&quot;;
    &#x5B;CsvColumn(&quot;pay&quot;)] public decimal Pay { get; set; }
    &#x5B;CsvColumn(Optional = true)] public string Region { get; set; } = &quot;n/a&quot;;
}

&#x5B;CsvRecord]
public partial class Account
{
    &#x5B;CsvColumn(Index = 0)] public int Id { get; set; }
    &#x5B;CsvColumn(Index = 1)] public string Name { get; set; } = &quot;&quot;;
    &#x5B;CsvColumn(Index = 2)] public decimal Balance { get; set; }
}
</pre></div>


<p class="wp-block-paragraph">Differences you will notice: the date column is written as ISO 8601 (<code>2022-03-14T00:00:00.0000000</code>) by default, a missing optional column keeps the property initializer and header names are matched ignoring case. Run with a file that had a text Id and a stray quote, the <code>messy</code> options skipped the bad records and reported them. Not tested in v34: <code>dynamic</code> records, non-UTF-8 encodings and the parallel readers.</p>



<h2 class="wp-block-heading" id="result">What the output looks like</h2>



<p class="wp-block-paragraph">Running the 33.1.0 samples printed this (shortened where noted):</p>


<div class="wp-block-syntaxhighlighter-code ">
&#8212; read to class
1 | Asha | 5200.50 | 2022-03-14
2 | Ravi | null | 2021-11-01
3 | Smith, John | 4800 | 2020-07-30
&#8212; ClassMap, de-DE
1 | Asha | 5200.50
2 | Ravi | 4800.00
&#8212; bad data
OK 1 | Asha | 5200
OK 4 | Omar | 3900
ERR row 3: cannot convert &#039;x&#039; for Id
ERR row 4: cannot convert &#039;&#039; for JoinDate
&#8212; default strictness (bad.csv)
TypeConverterException: The conversion cannot be performed.
&#8212; header mismatch
HeaderValidationException: Header with name &#039;Name&#039;[0] was not found.
&#8212; write
Id,Name,Salary,JoinDate
1,Asha,5200.5,2022-03-14
2,&quot;Smith, John&quot;,,2020-07-30
</div>


<h2 class="wp-block-heading" id="troubleshooting">Common problems and fixes</h2>



<ul class="wp-block-list">
<li><strong><code>HeaderValidationException: Header with name 'X' was not found</code></strong>: the header text does not match the property. Fix it with <code>ClassMap</code> and <code>.Name("...")</code>, or set <code>HeaderValidated = null</code> if the column is truly optional.</li>

<li><strong><code>TypeConverterException</code> on an empty value</strong>: an empty field cannot become <code>int</code> or <code>DateTime</code>. Use <code>int?</code> or <code>DateTime?</code>, or <code>.Default(...)</code> in a ClassMap.</li>

<li><strong>Numbers read wrongly or throw</strong>: culture mismatch. <code>1.234,56</code> needs a culture like <code>de-DE</code>; machine-made files usually need <code>InvariantCulture</code>.</li>

<li><strong>The first header is not found although it looks right</strong>: a byte order mark or a trailing space. Open <code>StreamReader</code> with the right encoding, and trim headers with <code>PrepareHeaderForMatch = args =&gt; args.Header.Trim().ToLower()</code> in the configuration (not tested here).</li>

<li><strong><code>MissingFieldException</code></strong>: a row has fewer fields than the header. Set <code>MissingFieldFound = null</code> or log it, as in Step 4.</li>

<li><strong>Semicolon or tab separated file reads as one column</strong>: set <code>Delimiter = ";"</code> (or <code>"\t"</code>) in <code>CsvConfiguration</code>.</li>

<li><strong>Code from an old tutorial does not compile after upgrading</strong>: version 34 removed <code>CsvConfiguration</code> and <code>ClassMap</code>. Pin 33.1.0 or follow the migration guide.</li>
</ul>



<h2 class="wp-block-heading" id="faq">Frequently asked questions</h2>



<h3 class="wp-block-heading">How do I read a CSV file in C# without a library?</h3>



<p class="wp-block-paragraph">You can use <code>StreamReader</code> with <code>Split</code> or <code>TextFieldParser</code>, but quoted fields with commas and line breaks make that fragile. See the general comparison in the linked post on reading CSV in .NET Core. CsvHelper removes that work.</p>



<h3 class="wp-block-heading">Which CsvHelper version should I use?</h3>



<p class="wp-block-paragraph">Use 33.1.0 if you maintain existing code or follow older tutorials. Use 34.x for new projects on .NET 8 or later, after reading its migration guide, because the API is different and not source compatible.</p>



<h3 class="wp-block-heading">How do I skip bad rows instead of failing the whole file?</h3>



<p class="wp-block-paragraph">In 33.x set <code>ReadingExceptionOccurred</code> to log the error and return <code>false</code>, and set <code>MissingFieldFound</code> and <code>HeaderValidated</code> to <code>null</code> as needed. In 34.x use <code>OnRecordError</code> and return <code>true</code> to skip the record.</p>



<h2 class="wp-block-heading" id="summary">Summary</h2>



<p class="wp-block-paragraph">To read a CSV file in C#, create a <code>CsvReader</code> with the right culture, map rows to a class with <code>GetRecords&lt;T&gt;()</code>, use <code>ClassMap</code> when headers differ, and handle missing and bad data through the configuration callbacks. Stream large files with <code>GetRecordsAsync</code>. Tested here: CsvHelper 33.1.0 reading, ClassMap, culture, no header, bad data, dynamic, records, async and writing, plus the 34.1.0 equivalents except dynamic. Not tested: very large files, non-UTF-8 encodings, fixed-width files, and the header trimming option.</p>



<div class="wp-block-group has-background" style="border-radius:8px;background-color:#b6d9ac;padding-top:20px;padding-right:24px;padding-bottom:20px;padding-left:24px"><div class="wp-block-group__inner-container is-layout-constrained wp-container-core-group-is-layout-0d2d72cd wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph" style="font-size:20px"><strong>Found this useful?</strong></p>



<p class="wp-block-paragraph">Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.</p>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noopener">Subscribe to TheCodeBuzz</a></div>
</div>
</div></div>



<script type="application/ld+json">{"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I read a CSV file in C# without a library?", "acceptedAnswer": {"@type": "Answer", "text": "You can use StreamReader with Split or TextFieldParser, but quoted fields with commas and line breaks make that fragile. See the general comparison in the linked post on reading CSV in .NET Core. CsvHelper removes that work."}}, {"@type": "Question", "name": "Which CsvHelper version should I use?", "acceptedAnswer": {"@type": "Answer", "text": "Use 33.1.0 if you maintain existing code or follow older tutorials. Use 34.x for new projects on .NET 8 or later, after reading its migration guide, because the API is different and not source compatible."}}, {"@type": "Question", "name": "How do I skip bad rows instead of failing the whole file?", "acceptedAnswer": {"@type": "Answer", "text": "In 33.x set ReadingExceptionOccurred to log the error and return false, and set MissingFieldFound and HeaderValidated to null as needed. In 34.x use OnRecordError and return true to skip the record."}}]}</script><p>The post <a href="https://thecodebuzz.com/csvhelper-read-csv-files-in-csharp-net-core/">CsvHelper in C#: Read and Write CSV Files in .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/csvhelper-read-csv-files-in-csharp-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ASP.NET Core 502 API Gateway error in Google Cloud</title>
		<link>https://thecodebuzz.com/asp-net-core-502-api-gateway-error-in-google-cloud/</link>
					<comments>https://thecodebuzz.com/asp-net-core-502-api-gateway-error-in-google-cloud/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 10 Jul 2022 17:11:00 +0000</pubDate>
				<category><![CDATA[Tips]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=19035</guid>

					<description><![CDATA[<p>ASP.NET Core 502 API Gateway error in Google Cloud Today in this article, we will cover below aspects, Issue Description ASP.NET Core deployment gives 502 errors with the below logs after the frequent intervals. ASP.NET Core 502 API Gateway error with application shutdown is most visible in the logs Error &#8220;Application is shutting down&#8221; Resolution [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/asp-net-core-502-api-gateway-error-in-google-cloud/">ASP.NET Core 502 API Gateway error in Google Cloud</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">ASP.NET Core 502 API Gateway error in Google Cloud</h1>



<p class="wp-block-paragraph">Today in this article, we will cover below aspects,</p>



<p class="wp-block-paragraph"></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-issue-description">Issue Description</a></li><li><a href="#aioseo-resolution">Resolution</a></li><li><a href="#aioseo-solution1-increase-memory-allocation">Solution1 &#8211; Increase Memory Allocation</a></li><li><a href="#aioseo-solution2-liveness-and-readiness-health-check-probe">Solution2 &#8211; Liveness and readiness Health check probe</a></li><li><a href="#aioseo-solution3-health-route-with-empty-route-or-controller">Solution3 &#8211; Health route with empty route or controller &#8220;</a></li></ul></div>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-issue-description">Issue Description</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">ASP.NET Core deployment gives 502 errors with the below logs after the frequent intervals.</p>



<p class="wp-block-paragraph"> ASP.NET Core 502 API Gateway error with application shutdown is most visible in the logs</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong><em>Error </em></strong></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><span style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">&#8220;Application is shutting down&#8221;</span></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-resolution">Resolution</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">There could be multiple reasons for the application shutdown. Please make sure to validate the below steps.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-solution1-increase-memory-allocation">Solution1 &#8211; Increase Memory Allocation </h2>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li>Application shutdown could occur mainly if the application is loaded with more responsibility than it can handle.</li>



<li>Please make sure you allocate enough memory or CPU depending on the number of requests API can handle. A good load test on API should provide the request load metrics of API.</li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please update the <strong>YAML </strong>file,</p>



<p class="wp-block-paragraph"></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [2,3,4]; title: ; notranslate">
resources:
    cpu: 2
    memory_gb: 2
    disk_size_gb: 10
</pre></div>


<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">If the above properties are not provided then the cloud environment will select default settings. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>Example</strong> &#8211; <strong><em>1 CPU or 1 GB </em></strong>memory etc.</p>



<p class="wp-block-paragraph"></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Note &#8211; Application default settings could be less sustainable for your API. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Specifically if API handles a large load or more requests then above settings will need to be updated. </p>
</blockquote>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">If you have tried the above option already still see the issue surfacing then please look at the below few options.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-solution2-liveness-and-readiness-health-check-probe">Solution2 &#8211; Liveness and readiness Health check probe</h2>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li>Google Cloud uses liveness checks to confirm VM and the Docker container are healthy and running. </li>



<li>Instances with unhealthy status are killed and restarted. </li>



<li>In such a case please make sure the Liveness probe is successful as per the configuration.</li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>Example,</strong></p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-preformatted"> liveness_check:
  path: "/liveness_check"
  check_interval_sec: 30
  timeout_sec: 4
  failure_threshold: 2
  success_threshold: 2</pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>Or </strong></p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-preformatted">liveness_check:
  path: "/healthcheck"
  check_interval_sec: 30
  timeout_sec: 4
  failure_threshold: 2
  success_threshold: 2</pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>The &#8220;path&#8221;  </strong>variable can be defined by the API developer as required. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please make sure you have a &#8220;path&#8221;: defined correctly.  Example. &#8220;<em><strong>/liveness_check&#8221;</strong></em> or &#8220;/<em><strong>healthcheck</strong></em>&#8221; routes should return HTTP status 200 or OK response only.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">For any reason, if <strong><em>&#8220;/healthcheck&#8221;</em></strong> is not defined or produces non-OK status then the google app engine initiates the container killing and restarting the container.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">You can add health to ASP.NET Core in two simple easy steps which are explained in the below article.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-solution3-health-route-with-empty-route-or-controller">Solution3 &#8211; Health route with empty route or controller &#8220;</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">If your API doesn&#8217;t specify any health route, then it is possible sometimes the Google app engine might look for the root route &#8220;/&#8221;. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">If you have any custom health check then please specify the same else make sure you point to the correct health check here in the path: <em><strong>&#8220;/healthcheck&#8221;</strong></em></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Having a controller with an empty route &#8220;sometimes will resolve the issue. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please try this too as one of the solutions to fix the issue.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong><em>References: </em></strong></p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/add-health-check-asp-net-core-mvc-ihealthcheck/" target="_blank" rel="noreferrer noopener" title="Add Health Check in ASP.NET Core Applications"><strong><em>Add Health Check in ASP.NET Core Applications</em></strong></a></li>



<li><a href="https://www.thecodebuzz.com/health-check-entity-framework-database-efcore-asp-net-core/" title="Health Check Entity Framework Database in ASP.NET Core" target="_blank" rel="noreferrer noopener"><em><strong>Health Check Entity Framework Database in ASP.NET Core</strong></em></a></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Did I miss anything else in these resolution steps?</p>



<p class="wp-block-paragraph">Did the above steps resolve your issue? Please sound off your comments below!</p>



<p class="wp-block-paragraph">Happy Coding !!</p>



<hr>



<p class="wp-block-paragraph"></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p><p>The post <a href="https://thecodebuzz.com/asp-net-core-502-api-gateway-error-in-google-cloud/">ASP.NET Core 502 API Gateway error in Google Cloud</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/asp-net-core-502-api-gateway-error-in-google-cloud/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>JWT bearer Authorization in Swagger OpenAPI</title>
		<link>https://thecodebuzz.com/jwt-authorization-token-swagger-open-api-asp-net-core-3-0/</link>
					<comments>https://thecodebuzz.com/jwt-authorization-token-swagger-open-api-asp-net-core-3-0/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 16 Jun 2022 22:52:00 +0000</pubDate>
				<category><![CDATA[API Best Practices]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[.net core 3.0 swagger bearer token]]></category>
		<category><![CDATA[Add JWT swagger net core 3.0 swagger JWT net Core 3.0]]></category>
		<category><![CDATA[add swagger to web api net core]]></category>
		<category><![CDATA[addsecuritydefinition swagger 5]]></category>
		<category><![CDATA[asp.net core 2.0 swagger]]></category>
		<category><![CDATA[asp.net core 3.0 swagger]]></category>
		<category><![CDATA[asp.net core 3.1 swagger]]></category>
		<category><![CDATA[asp.net core 5 swagger]]></category>
		<category><![CDATA[asp.net core swagger authentication]]></category>
		<category><![CDATA[asp.net core swagger basic authentication ioperationfilter ]]></category>
		<category><![CDATA[asp.net core swagger bearer token]]></category>
		<category><![CDATA[asp.net core swagger not working]]></category>
		<category><![CDATA[asp.net core swagger oauth2]]></category>
		<category><![CDATA[Failed to load API definition]]></category>
		<category><![CDATA[ioperationfilter swagger .net core 3]]></category>
		<category><![CDATA[ioperationfilter swagger .net core 3.1]]></category>
		<category><![CDATA[ioperationfilter swagger .net core 5]]></category>
		<category><![CDATA[JWT aspnetcore swagger]]></category>
		<category><![CDATA[JWT net Core 3.0 swagger]]></category>
		<category><![CDATA[JWT swagger net core 3.0]]></category>
		<category><![CDATA[swagger .net 5]]></category>
		<category><![CDATA[swagger .net core 3]]></category>
		<category><![CDATA[swagger .net core 3.1]]></category>
		<category><![CDATA[swagger addsecurityrequirement]]></category>
		<category><![CDATA[swagger JWT authentication net core 3.0]]></category>
		<category><![CDATA[swagger jwt authorization]]></category>
		<category><![CDATA[swagger jwt bearer]]></category>
		<category><![CDATA[swagger jwt net Core]]></category>
		<category><![CDATA[swagger webapi JWT]]></category>
		<category><![CDATA[Swashbuckle 3.1 swagger]]></category>
		<category><![CDATA[swashbuckle 5]]></category>
		<category><![CDATA[swashbuckle jwt aspnetcore 3.0]]></category>
		<category><![CDATA[swashbuckle swagger]]></category>
		<category><![CDATA[swashbuckle swagger .NET 5]]></category>
		<category><![CDATA[swashbuckle swagger annotations]]></category>
		<category><![CDATA[swashbuckle swagger example]]></category>
		<category><![CDATA[swashbuckle swagger example .net 5]]></category>
		<category><![CDATA[swashbuckle vs nswag]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=5981</guid>

					<description><![CDATA[<p>JWT bearer Authorization in Swagger OpenAPI In this article, we will learn &#8211; how to enable JWT bearer Authorization in Swagger OpenAPI definition in API projects to execute various operations via swagger UI. Today in this article we will cover below, As we know Open API specification or Swagger V3.0 lets you define the different [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/jwt-authorization-token-swagger-open-api-asp-net-core-3-0/">JWT bearer Authorization in Swagger OpenAPI</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>JWT bearer Authorization in Swagger OpenAPI</strong></h1>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/10/JWT-autentication-token-swagger-swashbuckle-asp.netcore-with-jwt-token-bearer.jpg?fit=785%2C381&amp;ssl=1" alt="Use JWT Bearer Authorization Token in Swagger-OpenAPI" class="wp-image-5983" width="817" height="396" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/JWT-autentication-token-swagger-swashbuckle-asp.netcore-with-jwt-token-bearer.jpg 1906w, https://thecodebuzz.com/wp-content/uploads/2019/10/JWT-autentication-token-swagger-swashbuckle-asp.netcore-with-jwt-token-bearer-300x145.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/JWT-autentication-token-swagger-swashbuckle-asp.netcore-with-jwt-token-bearer-1024x496.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/10/JWT-autentication-token-swagger-swashbuckle-asp.netcore-with-jwt-token-bearer-768x372.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/JWT-autentication-token-swagger-swashbuckle-asp.netcore-with-jwt-token-bearer-1536x745.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/10/JWT-autentication-token-swagger-swashbuckle-asp.netcore-with-jwt-token-bearer-785x381.jpg 785w" sizes="auto, (max-width: 817px) 100vw, 817px" /></figure>



<p class="wp-block-paragraph">In this article, we will learn &#8211; how to enable JWT bearer Authorization in Swagger OpenAPI definition in API projects to execute various operations via swagger UI.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Today in this article we will cover below,</p>



<p class="wp-block-paragraph"></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-jwt-authorization-token-in-swagger">JWT Authorization Token in Swagger</a></li><li><a href="#aioseo-getting-started">Getting started</a></li><li><a href="#aioseo-step-1">Step 1- Define AddSecurityDefinition</a></li><li><a href="#aioseo-step-2">Step 2- Add AddSecurityRequirement</a></li><li><a href="#aioseo-jwt-json-web-token">What is JWT (JSON Web Token)</a></li><li><a href="#aioseo-response--success--200">Response – Success ( 200)</a></li><li><a href="#aioseo-response--unauthorized--401">Response – Unauthorized ( 401)</a></li><li><a href="#aioseo-understanding-global-vs-operation-level-scheme">Understanding Global Vs Operation level scheme</a><ul><li><a href="#aioseo-summary">Summary</a></li></ul></li></ul></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">As we know <em><strong>Open API specification</strong></em> or <em><strong>Swagger V3.0</strong></em> lets you define the different authentication types for an API like&nbsp;<em><strong><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/use-basic-authentication-swagger-net-core-webapi/" target="_blank">Basic authentication</a>,&nbsp;<a rel="noreferrer noopener" href="https://www.thecodebuzz.com/use-oauth-authorization-token-in-swagger-net-core/" target="_blank">OAuth2 Authentication</a>,</strong></em> JWT bearer, etc. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">In our last article, we learned how to <a href="https://www.thecodebuzz.com/swagger-api-documentation-in-net-core-3-0/" target="_blank" rel="noreferrer noopener"><strong><em>Enable Swagger/Open API documentation to ASP.NET Core</em></strong>  </a>API in simple 2-3 steps.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">We also learned <a href="https://www.thecodebuzz.com/jwt-authentication-in-asp-net-core-3-0-with-examples/" target="_blank" rel="noreferrer noopener"><strong><em>JWT Authentication in ASP.NET Core 3.1 or .NET 5.0  with examples</em></strong></a> in our last article.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-jwt-authorization-token-in-swagger"><strong>JWT Authorization Token in Swagger</strong></h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please kindly see the below article to understand the basic 2-3 steps workflow for enabling swagger in<strong><em> ASP.NET Core 3.1 or .NET 5</em>  or .NET 6</strong></p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/swagger-api-documentation-in-net-core-3-0/" target="_blank"><strong><em>Enable Swagger/Open API documentation to ASP.NET Core </em></strong></a></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please add two below methods&nbsp;as shown below,</p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong>AddSecurityDefinition()</strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong>AddSecurityRequirement()</strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>AddSecurityDefinition </strong>– This method lets you define how your API is secured by defining one or more security schemes. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><em>AddSecurityDefinition </em>method lets you enable the below authentication schemes. (One can use multiple security schemes too if needed.)</p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong><a href="https://www.thecodebuzz.com/use-basic-authentication-swagger-net-core-webapi/" target="_blank" rel="noreferrer noopener">Basic Authentication using BasicAuthScheme</a></strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong>JWT Bearer token using ApiKeyScheme</strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/use-oauth-authorization-token-in-swagger-net-core/" target="_blank">OAuth2 authentication using OAuth2Scheme</a></strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Please make a note that there are a few breaking changes introduced in the recent ASP.NET Core 3.1 Swagger supports if you are migrating from older version.</p>
</blockquote>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">A few major breaking changes for swagger in ASP.NET Core 3.1 and above are listed below,</p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><em>Info </em>class renamed <em>OpenApiInfo</em></li>
</ul>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><em>ApiKeyScheme</em> class renamed to <em>OpenApiSecurityScheme</em></li>
</ul>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><em>AddSecurityRequirement</em> method has been updated to take <em>OpenApiSecurityRequirement</em> as an object parameter etc.</li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-getting-started">Getting started </h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">You need the below Nuget package of <strong><em>Swashbuckle </em></strong>to work with ASP.NET Core.</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-preformatted has-medium-font-size"> PM&gt; Install-Package Swashbuckle.AspNetCore -Version 5.0.1 </pre>



<p class="wp-block-paragraph"></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Please use the latest available version of &#8216;<em><strong>Swashbuckle.AspNetCore</strong></em>&#8216; as and when available.</p>
</blockquote>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-step-1">Step 1</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>The addSecurityDefinition </strong>method is defined as below,</p>



<p class="wp-block-paragraph"></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [4,5]; title: ; notranslate">
c.AddSecurityDefinition(&quot;bearerAuth&quot;, new OpenApiSecurityScheme
                {
                    Name = &quot;Authorization&quot;,
                    Type = SecuritySchemeType.Http,
                    Scheme = &quot;bearer&quot;,
                    BearerFormat = &quot;JWT&quot;,
                    In = ParameterLocation.Header,
                    Description = &quot;JWT Authorization header using the Bearer scheme.&quot;
                });
</pre></div>


<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">In the above example, I have used the &#8216;Bearer&#8217; scheme with scheme type as ApiKey.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Usually, the JWT bearer secured token can be made available as an environment variable or Secret Storage or could be made available through the&nbsp;<a rel="noreferrer noopener" href="https://www.thecodebuzz.com/configuration-in-net-core-2-1/" target="_blank"><strong><em>DI using a configuration file</em></strong></a>.</p>
</blockquote>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-step-2">Step 2 </h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>AddSecurityRequirement</strong> &#8211; This method lets you control the given authentication scheme applied at either the Global level or Operation level.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please add the below code for <strong>AddSecurityRequirement</strong>()</p>



<p class="wp-block-paragraph"></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [12]; title: ; notranslate">
c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                          new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference 
                                { 
                                    Type = ReferenceType.SecurityScheme, 
                                    Id = &quot;bearerAuth&quot; 
                                }
                            },
                            new string&#x5B;] {}
                    }
                });
</pre></div>


<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Finally, the complete code for the <em><strong>ConfigureServices </strong></em>method is as below,</p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="781" src="https://www.thecodebuzz.com/wp-content/uploads/2021/09/Authorization-in-Swagger-OpenAPI-1024x781.jpg" alt="" class="wp-image-18140" srcset="https://thecodebuzz.com/wp-content/uploads/2021/09/Authorization-in-Swagger-OpenAPI-1024x781.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/09/Authorization-in-Swagger-OpenAPI-300x229.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/09/Authorization-in-Swagger-OpenAPI-768x586.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/09/Authorization-in-Swagger-OpenAPI-1536x1171.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/09/Authorization-in-Swagger-OpenAPI-682x520.jpg 682w, https://thecodebuzz.com/wp-content/uploads/2021/09/Authorization-in-Swagger-OpenAPI.jpg 1574w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong><em>Configure</em></strong>() method will remain as above,</p>



<p class="wp-block-paragraph"></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [8,9,10,11,12,13]; title: ; notranslate">
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();

            app.UseSwaggerUI(c =&gt;
            {
                c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;TestService&quot;);
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(x =&gt; x
               .AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =&gt;
            {
                endpoints.MapControllers();
            });
        }
</pre></div>


<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Authorize button will be enabled in the swagger UI as below. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">The security scheme configured here will be used by all routes decorated with Authorize attributes as this is enabled at the global level.</p>



<p class="wp-block-paragraph"><br></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="https://i1.wp.com/thecodebuzz.com/wp-content/uploads/2019/10/Authorize-button-Swagger-JWT-API-Documentations-.NETCore3.0.jpg?fit=785%2C442&amp;ssl=1" alt="AddSecurityRequirement swagger open API" class="wp-image-5984" width="567" height="319" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/Authorize-button-Swagger-JWT-API-Documentations-.NETCore3.0.jpg 1639w, https://thecodebuzz.com/wp-content/uploads/2019/10/Authorize-button-Swagger-JWT-API-Documentations-.NETCore3.0-300x169.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/Authorize-button-Swagger-JWT-API-Documentations-.NETCore3.0-1024x577.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/10/Authorize-button-Swagger-JWT-API-Documentations-.NETCore3.0-768x433.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/Authorize-button-Swagger-JWT-API-Documentations-.NETCore3.0-1536x866.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/10/Authorize-button-Swagger-JWT-API-Documentations-.NETCore3.0-785x443.jpg 785w" sizes="auto, (max-width: 567px) 100vw, 567px" /></figure>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please provide bearer value and click on Authorize. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Bearer token can be generated using a simple process and is discussed in our last article on&nbsp;<strong><em><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/jwt-authentication-in-net-core" target="_blank">JWT Authentication in .NET Core</a>.</em></strong></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-jwt-json-web-token">JWT (JSON Web Token)</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here let’s use the&nbsp;<strong><em><a href="https://www.thecodebuzz.com/jwt-authentication-in-asp-net-core-3-0-with-examples/" target="_blank" rel="noreferrer noopener" title="JWT Authentication in C# ASP.NET Core example">Generated JWT token</a>&nbsp;</em></strong>in the previous article which is as below,</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-preformatted has-normal-font-size">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzA5MDk3MDMsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0MzQxIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNDEifQ.Is7QtMiknbSYHq8MFryCfXW25C8oK9tFZlD2jHEQTuo</pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Let’s execute the API to validate the authentication and see if it is working fine.</p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="503" src="https://www.thecodebuzz.com/wp-content/uploads/2021/09/JWT-bearer-openapi-swagger-.net5_-1024x503.jpg" alt="AddSecurityDefinition swagger openapi" class="wp-image-18142" srcset="https://thecodebuzz.com/wp-content/uploads/2021/09/JWT-bearer-openapi-swagger-.net5_-1024x503.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/09/JWT-bearer-openapi-swagger-.net5_-300x147.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/09/JWT-bearer-openapi-swagger-.net5_-768x377.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/09/JWT-bearer-openapi-swagger-.net5_-785x386.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2021/09/JWT-bearer-openapi-swagger-.net5_.jpg 1176w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">When using an HTTP Authentication scheme,</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Note : If using<strong><em> SecuritySchemeType.ApiKey </em></strong>&#8211;  token part should be appended with ‘<em><strong>bearer</strong></em>’.</p>



<p class="wp-block-paragraph">Example:<span class="has-inline-color has-luminous-vivid-orange-color"> Bearer [token]</span></p>
</blockquote>



<p class="wp-block-paragraph"></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Note &#8211; If using <em><strong>SecuritySchemeType.Http</strong></em>  &#8211; token need to be used without &#8220;bearer&#8221;</p>
</blockquote>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">This authorization will be used for all swagger APIs that are attributed with&nbsp;the [Authorize]&nbsp;attribute due to the global settings defined above.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">This token will be used for all secured APIs until it’s valid.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-response--success--200">Response – Success ( 200)</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">After executing, please check the response below, we shall receive a successful response status (200: Ok)</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">We can see API decorated with [<strong><em>Authorize</em></strong>] keyword gets executed successfully from UI directly.</p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="https://i2.wp.com/thecodebuzz.com/wp-content/uploads/2019/10/Read-JWT-token-from-webapi-httpcontext.jpg?fit=785%2C233&amp;ssl=1" alt="authorization-bearer-token-in-a-swagger-openapi" class="wp-image-5988" width="559" height="166" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/Read-JWT-token-from-webapi-httpcontext.jpg 2560w, https://thecodebuzz.com/wp-content/uploads/2019/10/Read-JWT-token-from-webapi-httpcontext-300x89.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/Read-JWT-token-from-webapi-httpcontext-1024x304.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/10/Read-JWT-token-from-webapi-httpcontext-768x228.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/Read-JWT-token-from-webapi-httpcontext-1536x456.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/10/Read-JWT-token-from-webapi-httpcontext-2048x608.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2019/10/Read-JWT-token-from-webapi-httpcontext-785x233.jpg 785w" sizes="auto, (max-width: 559px) 100vw, 559px" /></figure>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="https://i2.wp.com/thecodebuzz.com/wp-content/uploads/2019/10/Get-JWT-autentication-token-swagger-token-Http-context.jpg?fit=785%2C493&amp;ssl=1" alt="authorization-bearer-token-in-a-swagger" class="wp-image-5991" width="565" height="355" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/Get-JWT-autentication-token-swagger-token-Http-context.jpg 1470w, https://thecodebuzz.com/wp-content/uploads/2019/10/Get-JWT-autentication-token-swagger-token-Http-context-300x189.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/Get-JWT-autentication-token-swagger-token-Http-context-1024x644.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/10/Get-JWT-autentication-token-swagger-token-Http-context-768x483.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/Get-JWT-autentication-token-swagger-token-Http-context-785x493.jpg 785w" sizes="auto, (max-width: 565px) 100vw, 565px" /></figure>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-response--unauthorized--401">Response – Unauthorized ( 401)</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">If the token value is invalid or expired &#8211;  You would receive&nbsp;<strong>401: Unauthorized</strong>&nbsp;error as below,</p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/10/jwt-swagger-invalid-token-error-The-token-is-expired.jpg?fit=785%2C326&amp;ssl=1" alt="authorization-bearer-token-openapi-swagger" class="wp-image-5993" width="545" height="225" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/jwt-swagger-invalid-token-error-The-token-is-expired.jpg 2225w, https://thecodebuzz.com/wp-content/uploads/2019/10/jwt-swagger-invalid-token-error-The-token-is-expired-300x125.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/jwt-swagger-invalid-token-error-The-token-is-expired-1024x425.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/10/jwt-swagger-invalid-token-error-The-token-is-expired-768x319.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/jwt-swagger-invalid-token-error-The-token-is-expired-1536x638.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/10/jwt-swagger-invalid-token-error-The-token-is-expired-2048x850.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2019/10/jwt-swagger-invalid-token-error-The-token-is-expired-785x326.jpg 785w" sizes="auto, (max-width: 545px) 100vw, 545px" /></figure>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-understanding-global-vs-operation-level-scheme">Understanding Global Vs Operation level scheme </h2>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong>Global Authentication scheme</strong></li>
</ul>



<p class="wp-block-paragraph">Above we have used a global authentication scheme, this scheme will be applied to all REST APIs within Controllers and can be executed on all APIs decorated with the [<strong><em>Authorize</em></strong>] attribute.</p>



<p class="wp-block-paragraph"></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">In <strong><em>AddSecurityRequirement</em></strong>() the array of <strong><em>scopes MUST be empty</em></strong> I.e new string[] {} for JWT  authorization.</p>



<p class="wp-block-paragraph"></p>
</blockquote>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong>Operation-level Authentication scheme</strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please see <a href="https://www.thecodebuzz.com/use-jwt-authorization-in-swagger-using-ioperationfilter-net-core/" target="_blank" rel="noreferrer noopener"><em><strong>Enable JWT authorization in Swagger at the Operation leve</strong></em>l</a> on how to enable the JWT authorization scheme at a specific operation level.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">That&#8217;s all! </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong><em>Other references</em></strong> :</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong><em><a href="https://www.thecodebuzz.com/swagger-api-documentation-in-net-core-3-0/" target="_blank" rel="noreferrer noopener">Swagger API Documentation in ASP.NET Core</a></em></strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong><em><a href="https://www.thecodebuzz.com/jwt-authentication-in-asp-net-core-3-0-with-examples/" target="_blank" rel="noreferrer noopener">JWT Authentication in ASP.NET Core with examples</a></em></strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph" style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size wp-block-paragraph"></p>



<p class="wp-block-paragraph" style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size wp-block-paragraph"></p>



<p class="has-medium-font-size wp-block-paragraph"><strong>Happy Coding </strong>!!</p>



<p class="wp-block-paragraph"></p>



<h4 class="wp-block-heading" id="aioseo-summary">Summary</h4>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">In this post, we learned new breaking changes with improved Swagger/ Open API document implementation. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">We also learned, how to add JWT bearer authorization to Swagger documentation. Swagger or OpenAPI describes the standards and specifications of RESTFul API documentation. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">It also helps to provide specifications around enabling authentication schemes <strong><em>BasicAuthScheme, ApiKeyScheme</em></strong>,<strong><em> and OAuth2Schem</em></strong>e to API using the Swashbuckle or <strong><em><a href="https://www.thecodebuzz.com/nswag-jwt-token-authorization-openapi-documentation-asp-net-core/" title="NSwag JWT Token Authorization OpenAPI Documentation in ASP.NET Core">NSwag </a></em></strong>tooling.</p>



<p class="wp-block-paragraph"></p>



<hr>



<p class="wp-block-paragraph"></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p><p>The post <a href="https://thecodebuzz.com/jwt-authorization-token-swagger-open-api-asp-net-core-3-0/">JWT bearer Authorization in Swagger OpenAPI</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/jwt-authorization-token-swagger-open-api-asp-net-core-3-0/feed/</wfw:commentRss>
			<slash:comments>16</slash:comments>
		
		
			</item>
		<item>
		<title>Implement Simple Retry pattern in C# .NET- Resiliency</title>
		<link>https://thecodebuzz.com/implement-retry-pattern-in-csharp-dotnet-resiliency/</link>
					<comments>https://thecodebuzz.com/implement-retry-pattern-in-csharp-dotnet-resiliency/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 22 May 2022 12:53:00 +0000</pubDate>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[c# retry logic on exception]]></category>
		<category><![CDATA[c# retry pattern async]]></category>
		<category><![CDATA[c# retry pattern example]]></category>
		<category><![CDATA[c# retry pattern polly]]></category>
		<category><![CDATA[retry design pattern java]]></category>
		<category><![CDATA[retry logic for api call in c#]]></category>
		<category><![CDATA[retry mechanism in c#]]></category>
		<category><![CDATA[retry pattern in microservices]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=22424</guid>

					<description><![CDATA[<p>Implement Simple Retry pattern in C# &#8211; Resiliency Today in this article we will see an easy-to-use Simple Retry pattern in C# .NET Retry pattern in C# which can be used for executing given business logic/code addressing multiple attempts to retry execution. If you have a requirement, for adding a resilient logic processing then the [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/implement-retry-pattern-in-csharp-dotnet-resiliency/">Implement Simple Retry pattern in C# .NET- Resiliency</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Implement Simple Retry pattern in C# &#8211; Resiliency</h1>



<figure class="wp-block-image size-large"><a href="https://www.thecodebuzz.com/implement-retry-pattern-in-csharp-dotnet-resiliency/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="1024" height="457" src="https://www.thecodebuzz.com/wp-content/uploads/2022/06/Implement-Simple-Retry-pattern-in-C-1024x457.jpg" alt="Implement Simple Retry pattern in C#" class="wp-image-22508" srcset="https://thecodebuzz.com/wp-content/uploads/2022/06/Implement-Simple-Retry-pattern-in-C-1024x457.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/06/Implement-Simple-Retry-pattern-in-C-300x134.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/06/Implement-Simple-Retry-pattern-in-C-768x343.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/06/Implement-Simple-Retry-pattern-in-C-785x351.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/06/Implement-Simple-Retry-pattern-in-C.jpg 1272w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>



<p class="wp-block-paragraph">Today in this article we will see an easy-to-use Simple Retry pattern in C# .NET Retry pattern in C# which can be used for executing given business logic/code addressing multiple attempts to retry execution.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">If you have a requirement, for adding a resilient logic processing then the code can retry attempting to execute the actions a few more times. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Such retries generally resolve the issues in the case of <strong><em>transient </em></strong>errors or any temporary issues giving the desired result for the request. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>Example 1</strong></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here is below a simple example of <em><strong>Retry </strong></em>logic using C# .NET which can be used to execute any of your custom logic bind to an action.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">I am using the Console C# application below where I have static methods defined.</p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large is-resized"><a href="https://www.thecodebuzz.com/implement-retry-pattern-in-csharp-dotnet-resiliency/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="1024" height="852" src="https://www.thecodebuzz.com/wp-content/uploads/2022/06/How-to-use-Retry-on-File-best-practices-CSharp-.NET_-1024x852.jpg" alt="Implement Simple Retry pattern in C#, polly retry example c#,
retry pattern in c#,
retry in catch block c#,
c# retry with timeout,
c# retry task with delay,
c# retry async task,
how to retry api call in c#,
c waitandretryasync," class="wp-image-22509" style="width:627px;height:521px" srcset="https://thecodebuzz.com/wp-content/uploads/2022/06/How-to-use-Retry-on-File-best-practices-CSharp-.NET_-1024x852.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/06/How-to-use-Retry-on-File-best-practices-CSharp-.NET_-300x250.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/06/How-to-use-Retry-on-File-best-practices-CSharp-.NET_-768x639.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/06/How-to-use-Retry-on-File-best-practices-CSharp-.NET_-625x520.jpg 625w, https://thecodebuzz.com/wp-content/uploads/2022/06/How-to-use-Retry-on-File-best-practices-CSharp-.NET_.jpg 1403w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Below is how we can use the above Retry method in C# Calle side code</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-preformatted has-medium-font-size">Retry(() =&gt;PerformFileProcessing(filePath), 3);</pre>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li>Here in the above example, <strong>action </strong>is mapped to the method -&gt;  <strong><em>PerformFileProcessing </em></strong>is a custom method/action that has some core logic. For example- it performs file operations like read or write.</li>
</ul>



<ul class="wp-block-list">
<li><strong><em>No of retry</em></strong> &#8211; For any exceptions method <strong>retries execution 3 times </strong></li>
</ul>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-code"><code>private static void PerformFileProcessing(string filePath)
        {
            using (FileStream fsStrean = File.Create(filePath))
            {
                byte&#91;] info = new UTF8Encoding(true).GetBytes("This is test file.");
                // Add details to the file.
                fsStrean.Write(info1, 0, info.Length);
            }
        }</code></pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>Example 2</strong></p>



<p class="wp-block-paragraph"><br>Alternatively, the below logic can be used for performing the retry.</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-code"><code>private const int NumberOfRetries = 3;
  for (int i=1; i &lt;= NumberOfRetries; ++i) {
    try {
        // Perfrom your business logic here
        break; // When done, break the  loop
        }
    catch (IOException e) when (i &lt;= NumberOfRetries) {
    }
}</code></pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">In the catch block, if needed, you can add a time delay to retry with a timeout so that each retry happens with some delay.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Retry logic comes in handy on many occasions especially if you are dealing with shared resources. Most transient errors are common examples of issues related to shared resources. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Such transient errors get auto corrected and hence retrying the logic sometimes resolves the issues. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Before retrying the logic, make sure the object is not in a faulted state and you use the clean object in the logic.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">You can use the Polly library to implement the HTTP request retry mechanism easily. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Please visit this article for more details,</p>



<p class="wp-block-paragraph"></p>



<ul class="has-medium-font-size wp-block-list">
<li><a href="https://www.thecodebuzz.com/httpclient-resiliency-http-polly-csharp-netcore/" target="_blank" rel="noopener" title="Polly-Implement HTTPClient Retry resiliency using Polly">Polly-Implement HTTPClient Retry resiliency using Polly</a></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph" style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size wp-block-paragraph"></p>



<p class="wp-block-paragraph" style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size wp-block-paragraph"></p>



<p class="has-medium-font-size wp-block-paragraph"><strong>Happy Coding </strong>!!</p>



<p class="wp-block-paragraph"></p>



<hr>



<p class="wp-block-paragraph"></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p><p>The post <a href="https://thecodebuzz.com/implement-retry-pattern-in-csharp-dotnet-resiliency/">Implement Simple Retry pattern in C# .NET- Resiliency</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/implement-retry-pattern-in-csharp-dotnet-resiliency/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
