
<?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>.Net Core &#8211; CodeInDotNet</title>
	<atom:link href="https://www.codeindotnet.com/category/dotnet-core/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codeindotnet.com</link>
	<description>C# Dot Net Programming tutorial &#38; code examples</description>
	<lastBuildDate>Mon, 08 Sep 2025 16:11:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.codeindotnet.com/wp-content/uploads/2021/04/SiteIcon.png</url>
	<title>.Net Core &#8211; CodeInDotNet</title>
	<link>https://www.codeindotnet.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>What is NullReferenceException? Complete Guide to Understanding, Fixing, and Preventing Null Reference Errors in C#</title>
		<link>https://www.codeindotnet.com/what-is-nullreferenceexception-complete-guide-fixing-preventing/</link>
					<comments>https://www.codeindotnet.com/what-is-nullreferenceexception-complete-guide-fixing-preventing/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 08 Sep 2025 16:11:18 +0000</pubDate>
				<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=10814</guid>

					<description><![CDATA[NullReferenceException is one of the most common and frustrating runtime errors that .NET developers encounter. If you&#8217;ve ever seen the message &#8220;Object reference not set to an instance of an object,&#8221; you&#8217;ve experienced this exception firsthand. This comprehensive guide will walk you through everything you need to know about NullReferenceException, from understanding what causes it to implementing [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br><br>



<p><strong>NullReferenceException</strong> is one of the most common and frustrating runtime errors that .NET developers encounter. If you&#8217;ve ever seen the message &#8220;Object reference not set to an instance of an object,&#8221; you&#8217;ve experienced this exception firsthand. This comprehensive guide will walk you through everything you need to know about <strong>NullReferenceException</strong>, from understanding what causes it to implementing robust prevention strategies.</p>



<br><br>



<h2 class="wp-block-heading h2Cust1" id="what-is-nullreferenceexception"><strong>What is NullReferenceException?</strong></h2>



<br>



<p>A&nbsp;<strong>NullReferenceException</strong>&nbsp;(often abbreviated as NRE) occurs when your program attempts to access a member (such as a method or property) on a reference variable that currently holds a&nbsp;<strong>null reference</strong>. In simple terms, you&#8217;re trying to use something that doesn&#8217;t exist &#8211; like asking someone who isn&#8217;t there to do something for you.<a rel="noreferrer noopener" target="_blank" href="https://www.tutorialsteacher.com/articles/nullreferenceexception-in-csharp"></a></p>



<p>In .NET,&nbsp;<strong>reference types</strong>&nbsp;(such as classes, strings, and arrays) store references to objects in memory rather than the actual values. When a reference variable doesn&#8217;t point to any object, it contains a&nbsp;<strong>null value</strong>. The&nbsp;<strong>null reference</strong>&nbsp;serves as a way to indicate that a variable has no meaningful value or that an object is absent.<a rel="noreferrer noopener" target="_blank" href="https://pvs-studio.com/en/blog/posts/csharp/1049/"></a></p>



<p>When you attempt to&nbsp;<strong>dereference</strong>&nbsp;a&nbsp;<strong>null reference</strong>&nbsp;by accessing its members using the dot operator (.), the .NET runtime throws a&nbsp;<strong>NullReferenceException</strong>.<a rel="noreferrer noopener" target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=net-9.0"></a></p>



<br>
<div style="padding: 1.25rem 1.25rem 1.25rem 1.25rem;box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey;margin-bottom: 1.25rem;border-radius: 0.625rem;">
	<div style="margin-bottom: 0.375rem;">
		<span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>Interview Questions And Answers: </i></b></span>
		<a href="/oops-interview-questions-answers/" target="_blank" rel="noreferrer noopener"><strong>OOPs</strong></a>, 
		<a href="/csharp-interview-questions-answers/" target="_blank" rel="noreferrer noopener"><strong>C#</strong></a>, 
		<a href="/web-api-interview-questions-answers/" target="_blank" rel="noreferrer noopener"><strong>Web API</strong></a>, 
		<a href="/sql-interview-questions-answers/" target="_blank" rel="noreferrer noopener"><strong>SQL Database</strong></a>, 
		<a href="/entity-framework-interview-questions-answers/"><strong>Entity Framework</strong></a>
		
	</div>
</div>



<br><br>



<h2 class="wp-block-heading h2Cust1" id="common-causes-of-nullreferenceexception"><strong>Common Causes of NullReferenceException</strong></h2>



<p class="custp1">Understanding the root causes of&nbsp;<strong>null reference errors</strong>&nbsp;is essential for effective debugging and prevention. Here are the most frequent scenarios that lead to&nbsp;<strong>NullReferenceException</strong>:<a rel="noreferrer noopener" target="_blank" href="https://learn.microsoft.com/en-us/answers/questions/944445/how-can-i-fix-the-error-system-nullreferenceexcept"></a></p>



<h3 class="wp-block-heading hLBRed" id="1-uninitialized-object-variables"><strong>1. Uninitialized Object Variables</strong></h3>



<p class="custp1">The most basic cause occurs when you declare a reference variable but forget to initialize it with an actual object:</p>



<pre class="pchl"><code><span class="key">string</span> message = null;
<span class="key">int</span> length = message.Length; <span class="com">// Throws NullReferenceException</span></code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="2-uninitialized-class-fields"><strong>2. Uninitialized Class Fields</strong></h3>



<p class="custp1">Class fields of reference types default to&nbsp;<strong>null</strong>&nbsp;if not explicitly initialized:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Person
{
    <span class="key">private</span> <span class="key">string</span> _name; <span class="com">// Defaults to null</span>
    
    <span class="key">public</span> <span class="key">void</span> DisplayName()
    {
        Console.WriteLine(_name.Length); <span class="com">// NullReferenceException</span>
    }
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="3-method-returning-null"><strong>3. Method Returning Null</strong></h3>



<p class="custp1">When methods return&nbsp;<strong>null</strong>&nbsp;values and you don&#8217;t check before using the result:</p>



<pre class="pchl"><code><span class="key">public</span> Person FindPerson(<span class="key">int</span> id)
{
    <span class="com">// Returns null if person not found</span>
    <span class="key">return</span> database.FirstOrDefault(p =&gt p.Id == id);
}

<span class="key">var</span> person = FindPerson(123);
Console.WriteLine(person.Name); <span class="com">// Potential NullReferenceException</span></code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="4-method-chaining-with-null-values"><strong>4. Method Chaining with Null Values</strong></h3>



<p class="custp1"><strong>Method chaining</strong>&nbsp;becomes dangerous when any link in the chain returns&nbsp;<strong>null</strong>:</p>



<pre class="pchl"><code><span class="key">var</span> street = service.GetUser().Address.Street; <span class="com">// Any part could be null</span></code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="5-array-elements-containing-null"><strong>5. Array Elements Containing Null</strong></h3>



<p class="custp1">Arrays can contain&nbsp;<strong>null elements</strong>, leading to exceptions during iteration:</p>



<pre class="pchl"><code>string[] names = { <span class="str">"Alice"</span>, <span class="key">null</span>, <span class="str">"Bob"</span> };
<span class="key">foreach</span> (<span class="key">var</span> name <span class="key">in</span> names)
{
    Console.WriteLine(name.Length); <span class="com">// Throws exception on null element</span>
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="6-forgetting-component-assignment-unity-development"><strong>6. Forgetting Component Assignment (Unity Development)</strong></h3>



<p class="custp1">In&nbsp;<strong>Unity development</strong>, a common cause is forgetting to assign components in the Inspector:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> PlayerController : MonoBehaviour
{
    <span class="key">public</span> Transform playerTransform; <span class="com">// Not assigned in Inspector</span>
    
    <span class="key">void</span> Start()
    {
        playerTransform.position = Vector3.zero; <span class="com">// NullReferenceException</span>
    }
} </code></pre>



<br><br><br><br>



<h2 class="wp-block-heading h2Cust1" id="how-to-fix-nullreferenceexception"><strong>How to Fix NullReferenceException</strong></h2>



<p class="custp1">Fixing&nbsp;<strong>null reference errors</strong>&nbsp;requires systematic debugging and proper&nbsp;<strong>null handling</strong>. Here&#8217;s a step-by-step approach to resolve these issues:<a rel="noreferrer noopener" target="_blank" href="https://sentry.io/answers/nullreferenceexception-c-sharp/"></a></p>



<h3 class="wp-block-heading hLBRed" id="step-1-identify-the-exact-location"><strong>1. Identify the Exact Location</strong></h3>



<p class="custp1">The&nbsp;<strong>exception message</strong>&nbsp;typically indicates the exact line and method where the error occurred:</p>



<pre class="pchl"><code>NullReferenceException: Object reference not set to an instance of an object
at Example.Start() [0x0000b] in /Unity/projects/nre/Assets/Example.cs:10 </code></pre>



<p>This tells you that line 10 in the Example.cs file is where the problem occurs.<a rel="noreferrer noopener" target="_blank" href="https://docs.unity3d.com/550/Documentation/Manual/NullReferenceException.html"></a></p>



<br>



<h3 class="wp-block-heading hLBRed" id="step-2-use-debugging-tools"><strong>2. Use Debugging Tools</strong></h3>



<p class="custp1">Modern IDEs like&nbsp;<strong>Visual Studio</strong>&nbsp;provide powerful debugging capabilities:</p>



<ul class="wp-block-list ol1">
<li>Set&nbsp;<strong>breakpoints</strong>&nbsp;before the problematic line</li>



<li>Use the&nbsp;<strong>debugger</strong>&nbsp;to inspect variable values</li>



<li>Leverage <strong>Null Reference Analysis</strong> in Visual Studio to identify which specific object is <strong>null</strong><a href="https://blog.elmah.io/debugging-system-nullreferenceexception-object-reference-not-set-to-an-instance-of-an-object/" target="_blank" rel="noreferrer noopener"></a></li>
</ul>



<br>



<h3 class="wp-block-heading hLBRed" id="step-3-implement-null-checks"><strong>3. Implement Null Checks</strong></h3>



<p class="custp1">The most straightforward fix is adding&nbsp;<strong>explicit null checks</strong>:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> DisplayUserName(User user)
{
    <span style="background:#f2f19d;"><span class="key">if</span> (user != <span class="key">null</span>)</span>
    {
        Console.WriteLine(user.Name);
    }
    <span class="key">else</span>
    {
        Console.WriteLine(<span class="str">"User is null"</span>);
    }
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="step-4-use-safe-navigation-patterns"><strong>4. Use Safe Navigation Patterns</strong></h3>



<p class="custp1"><strong>C# 6.0</strong>&nbsp;introduced&nbsp;<strong>null-conditional operators</strong>&nbsp;that provide elegant solutions for&nbsp;<strong>null safety</strong>:</p>



<pre class="pchl"><code><span class="com">// Using null-conditional operator (?.)</span>
<span class="key">var</span> userName = user<span style="background:#f2f19d;">?</span>.Name;

<span class="com">// Chaining null-conditional operators</span>
<span class="key">var</span> street = user<span style="background:#f2f19d;">?</span>.Address<span style="background:#f2f19d;">?</span>.Street;

<span class="com">// Null-conditional with indexer</span>
<span class="key">var</span> firstItem = collection<span style="background:#f2f19d;">?</span>[0]; </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="step-5-provide-default-values"><strong>5. Provide Default Values</strong></h3>



<p class="custp1">Use the&nbsp;<strong>null-coalescing operator</strong>&nbsp;(??) to provide fallback values:</p>



<pre class="pchl"><code><span class="key">string</span> displayName = user?.Name <span style="background:#f2f19d;">??</span> <span class="str">"Unknown User"</span>;
<span class="key">var</span> items = collection <span style="background:#f2f19d;">??</span> <span class="key">new</span> List&lt;<span class="key">string</span>&gt(); </code></pre>



<br><br>



<br><br><br>



<h2 class="wp-block-heading h2Cust1" id="advanced-debugging-techniques"><strong>Advanced Debugging Techniques</strong></h2>



<br>



<h3 class="wp-block-heading hLBRed" id="using-debug-assert-for-development"><strong><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-black-color">1.</mark> Using Debug.Assert for Development</strong></h3>



<p class="custp1"><strong>Debug.Assert</strong>&nbsp;helps catch&nbsp;<strong>null references</strong>&nbsp;early during development:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ProcessUser(User user)
{
    Debug.Assert(user != <span class="key">null</span>, <span class="str">"User should not be null"</span>);
    <span class="com">// Process user safely</span>
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="exception-handling-with-try-catch"><strong>2. Exception Handling with Try-Catch</strong></h3>



<p class="custp1">While not recommended as a primary solution,&nbsp;<strong>try-catch blocks</strong>&nbsp;can handle unexpected&nbsp;<strong>null references</strong>:</p>



<pre class="pchl"><code><span class="key">try</span>
{
    <span class="key">var</span> result = service.GetData().ProcessValue();
}
<span class="key">catch</span> (NullReferenceException ex)
{
    Logger.LogError(<span class="str">"Unexpected null reference: "</span> + ex.Message);
    <span class="com">// Handle gracefully</span>
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="using-nullable-reference-types"><strong>3. Using Nullable Reference Types</strong></h3>



<p class="custp1"><strong>C# 8.0</strong>&nbsp;introduced&nbsp;<strong>nullable reference types</strong>&nbsp;that help identify potential&nbsp;<strong>null reference issues</strong>&nbsp;at compile time:</p>



<pre class="pchl"><code>#nullable enable

<span class="key">public</span> <span class="key">class</span> User
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; } = string.Empty; <span class="com">// Non-nullable</span>
    <span class="key">public</span> string? Email { get; set; } <span class="com">// Nullable</span>
} </code></pre>



<br><br><br><br>



<h2 class="wp-block-heading h2Cust1" id="ways-to-prevent-nullreferenceexception"><strong>Ways to Prevent NullReferenceException</strong></h2>



<p class="custp1">Prevention is always better than fixing&nbsp;<strong>null reference errors</strong>&nbsp;after they occur. Here are proven strategies to avoid&nbsp;<strong>NullReferenceException</strong>:<a rel="noreferrer noopener" target="_blank" href="https://www.wayline.io/blog/fixing-nullreferenceexception-unity-guide"></a></p>



<h3 class="wp-block-heading hLBRed" id="1-defensive-programming"><strong>1. Defensive Programming</strong></h3>



<p class="custp1">Always assume that references might be&nbsp;<strong>null</strong>&nbsp;and implement appropriate checks:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">decimal</span> CalculateTotal(Order order)
{
    <span class="key">if</span> (order == <span class="key">null</span>)
        <span class="key">throw</span> <span class="key">new</span> ArgumentNullException(nameof(order));
    
    <span class="key">if</span> (order.Items == <span class="key">null</span>)
        <span class="key">return</span> 0;
    
    <span class="key">return</span> order.Items.Sum(item =&gt item?.Price ?? 0);
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="2-initialize-variables-properly"><strong>2. Initialize Variables Properly</strong></h3>



<p class="custp1">Ensure all reference variables are initialized when declared:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ShoppingCart
{
    <span class="key">public</span> List&lt;Item&gt Items { get; set; } = <span class="key">new</span> List&lt;Item&gt(); <span class="com">// Initialize immediately</span>
    
    <span class="key">public</span> ShoppingCart()
    {
        <span class="com">// Constructor ensures proper initialization</span>
        Items = <span class="key">new</span> List&lt;Item&gt();
    }
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="3-use-constructor-injection"><strong>3. Use Constructor Injection</strong></h3>



<p class="custp1"><strong>Dependency injection</strong>&nbsp;makes dependencies explicit and ensures they&#8217;re not&nbsp;<strong>null</strong>:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> OrderService
{
    <span class="key">private</span> <span class="key">readonly</span> IRepository _repository;
    
    <span class="key">public</span> OrderService(IRepository repository)
    {
        _repository = repository ?? <span class="key">throw</span> <span class="key">new</span> ArgumentNullException(nameof(repository));
    }
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="4-implement-null-object-pattern"><strong>4. Implement Null Object Pattern</strong></h3>



<p class="custp1">Create default objects instead of returning&nbsp;<strong>null</strong>:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> NullUser : IUser
{
    <span class="key">public</span> <span class="key">string</span> Name =&gt <span class="str">"Guest"</span>;
    <span class="key">public</span> <span class="key">bool</span> IsValid =&gt false;
}

<span class="key">public</span> IUser GetUser(<span class="key">int</span> id)
{
    <span class="key">var</span> user = database.Find(id);
    <span class="key">return</span> user ?? <span class="key">new</span> NullUser(); <span class="com">// Never return null</span>
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="5-use-guard-clauses"><strong>5. Use Guard Clauses</strong></h3>



<p class="custp1">Implement&nbsp;<strong>guard clauses</strong>&nbsp;at the beginning of methods:</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ProcessOrder(Order order)
{
    <span class="key">if</span> (order == <span class="key">null</span>) return; <span class="com">// Early exit</span>
    <span class="key">if</span> (order.Items == <span class="key">null</span>) return;
    
    <span class="com">// Safe to proceed</span>
    <span class="key">foreach</span> (<span class="key">var</span> item <span class="key">in</span> order.Items)
    {
        ProcessItem(item);
    }
} </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="6-enable-nullable-reference-types"><strong>6. Enable Nullable Reference Types</strong></h3>



<p class="custp1">Configure your project to use&nbsp;<strong>nullable reference types</strong>&nbsp;for compile-time&nbsp;<strong>null safety</strong>:</p>



<pre class="pchl"><code>&lt;PropertyGroup&gt
    &lt;Nullable&gtenable&lt;/Nullable&gt
&lt;/PropertyGroup&gt </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed" id="7-use-modern-c-features"><strong>7. Use Modern C# Features</strong></h3>



<p class="custp1">Leverage <strong>pattern matching</strong> and other modern C# features for <strong>null safety</strong>:</p>



<pre class="pchl"><code><span class="com">// Pattern matching with null checks</span>
<span class="key">if</span> (user <span class="key">is</span> { Name: not <span class="key">null</span> } validUser)
{
    Console.WriteLine(validUser.Name);
}

<span class="com">// Null-coalescing assignment (C# 8.0)</span>
name ??= <span class="str">"Default Name"</span>; </code></pre>



<br><br><br><br>



<h2 class="wp-block-heading h2Cust1" id="debugging-tools-and-techniques"><strong>Debugging Tools and Techniques</strong></h2>



<br>



<h3 class="wp-block-heading hLBRed" id="visual-studio-debugging-features"><strong>1. Visual Studio Debugging Features</strong></h3>



<p class="custp1"><strong>Visual Studio</strong>&nbsp;provides excellent tools for debugging&nbsp;<strong>null reference exceptions</strong>:<a rel="noreferrer noopener" target="_blank" href="https://learn.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2022"></a></p>



<ul class="wp-block-list ol1">
<li><strong>Exception Helper</strong>&nbsp;shows detailed information about the exception</li>



<li><strong>Null Reference Analysis</strong>&nbsp;identifies which object is&nbsp;<strong>null</strong></li>



<li><strong>IntelliCode</strong>&nbsp;suggestions help prevent common&nbsp;<strong>null reference patterns</strong></li>
</ul>



<br>



<h3 class="wp-block-heading hLBRed" id="unity-specific-debugging"><strong>2. Unity-Specific Debugging</strong></h3>



<p class="custp1">For&nbsp;<strong>Unity developers</strong>, additional considerations include:<a rel="noreferrer noopener" target="_blank" href="https://docs.unity3d.com/6000.1/Documentation/Manual/null-reference-exception.html"></a></p>



<ul class="wp-block-list ol1">
<li>Use&nbsp;<strong>Unity&#8217;s Console</strong>&nbsp;to track&nbsp;<strong>null references</strong>&nbsp;in game objects</li>



<li>Leverage&nbsp;<strong>Unity&#8217;s Inspector</strong>&nbsp;to ensure component assignments</li>



<li>Implement&nbsp;<strong>null checks</strong>&nbsp;in MonoBehaviour lifecycle methods</li>
</ul>



<br>



<h3 class="wp-block-heading hLBRed" id="logging-and-monitoring"><strong>3. Logging and Monitoring</strong></h3>



<br>



<p>Implement comprehensive&nbsp;<strong>logging</strong>&nbsp;to track&nbsp;<strong>null reference issues</strong>&nbsp;in production:</p>



<pre class="pchl"><code><span class="key">public</span> User GetUser(<span class="key">int</span> id)
{
    <span class="key">try</span>
    {
        <span class="key">var</span> user = _repository.FindUser(id);
        <span class="key">if</span> (user == <span class="key">null</span>)
        {
            _logger.LogWarning($<span class="str">"User with ID {id} not found"</span>);
            <span class="key">return</span> null;
        }
        <span class="key">return</span> user;
    }
    <span class="key">catch</span> (Exception ex)
    {
        _logger.LogError(ex, $<span class="str">"Error retrieving user {id}"</span>);
        <span class="key">throw</span> ;
    }
} </code></pre>



<br><br><br><br>



<h2 class="wp-block-heading h2Cust1" id="best-practices-summary"><strong>Best Practices Summary</strong></h2>



<br>



<p>To effectively handle&nbsp;<strong>null reference exceptions</strong>, follow these&nbsp;<strong>best practices</strong>:<a rel="noreferrer noopener" target="_blank" href="https://dev.to/moh_moh701/guarding-against-null-in-c-best-practices-and-approaches-158i"></a></p>



<ol class="wp-block-list ol1">
<li><strong>Enable nullable reference types</strong>&nbsp;in new projects</li>



<li><strong>Initialize variables</strong>&nbsp;immediately when possible</li>



<li><strong>Use null-conditional operators</strong>&nbsp;(?.) for safe member access</li>



<li><strong>Implement guard clauses</strong>&nbsp;at method entry points</li>



<li><strong>Prefer exceptions over null returns</strong>&nbsp;when appropriate</li>



<li><strong>Use dependency injection</strong>&nbsp;to manage object lifecycles</li>



<li><strong>Write unit tests</strong>&nbsp;that cover null scenarios</li>



<li><strong>Document null behavior</strong>&nbsp;in method contracts</li>
</ol>



<br><br><br>



<h2 class="wp-block-heading h2Cust2" id="conclusion"><strong>Conclusion</strong></h2>



<br>



<p><strong>NullReferenceException</strong>&nbsp;may be one of the most common errors in .NET development, but it&#8217;s entirely preventable with proper techniques and awareness. By understanding what causes&nbsp;<strong>null reference errors</strong>, implementing robust&nbsp;<strong>debugging strategies</strong>, and following&nbsp;<strong>prevention best practices</strong>, you can significantly reduce these exceptions in your applications.</p>



<p>The key to mastering&nbsp;<strong>null safety</strong>&nbsp;lies in adopting a&nbsp;<strong>defensive programming mindset</strong>, leveraging modern C# features like&nbsp;<strong>nullable reference types</strong>&nbsp;and&nbsp;<strong>null-conditional operators</strong>, and implementing comprehensive&nbsp;<strong>null checking</strong>&nbsp;throughout your codebase. Remember that preventing&nbsp;<strong>null references</strong>&nbsp;is always more efficient and reliable than handling them after they occur.</p>



<p>With the techniques and strategies outlined in this guide, you&#8217;ll be well-equipped to write more robust, error-free C# applications that gracefully handle&nbsp;<strong>null scenarios</strong>&nbsp;without compromising functionality or user experience.</p>



<br><br>



<h2 class="wp-block-heading h2Cust2" id="frequently-asked-questions-faqs"><strong>Frequently Asked Questions (FAQs)</strong></h2>



<br>



<h3 class="wp-block-heading" id="what-does-object-reference-not-set-to-an-instance-of-an-object-mean"><strong>What does &#8220;Object reference not set to an instance of an object&#8221; mean?</strong></h3>



<p class="custp1">This error message indicates that you&#8217;re trying to use a reference variable that contains&nbsp;<strong>null</strong>&nbsp;instead of pointing to an actual object. The variable exists, but it doesn&#8217;t reference any object in memory.<a rel="noreferrer noopener" target="_blank" href="https://www.site24x7.com/learn/fixing-nullreferenceexception-and-argumentnullexception.html"></a></p>



<br>



<h3 class="wp-block-heading" id="how-do-i-find-which-object-is-null-in-a-method-chain"><strong>How do I find which object is null in a method chain?</strong></h3>



<p class="custp1">Break down the&nbsp;<strong>method chain</strong>&nbsp;into separate lines or use&nbsp;<strong>Visual Studio&#8217;s Null Reference Analysis</strong>&nbsp;feature. You can also use the&nbsp;<strong>null-conditional operator</strong>&nbsp;(?.) to safely navigate the chain.<a rel="noreferrer noopener" target="_blank" href="https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it"></a></p>



<br>



<h3 class="wp-block-heading" id="can-null-reference-exception-be-caught-and-handled"><strong>Can NullReferenceException be caught and handled?</strong></h3>



<p class="custp1">Yes, you can catch&nbsp;<strong>NullReferenceException</strong>&nbsp;using&nbsp;<strong>try-catch blocks</strong>, but this is generally not recommended as a primary solution. It&#8217;s better to prevent the exception through proper&nbsp;<strong>null checking</strong>.<a rel="noreferrer noopener" target="_blank" href="https://www.tutorialsteacher.com/articles/nullreferenceexception-in-csharp"></a></p>



<br>



<h3 class="wp-block-heading" id="whats-the-difference-between-null-conditional-operator-and-null-coalescing-operator"><strong>What&#8217;s the difference between null-conditional operator and null-coalescing operator?</strong></h3>



<p class="custp1">The&nbsp;<strong>null-conditional operator</strong>&nbsp;(?.) safely accesses members if the object is not null, while the&nbsp;<strong>null-coalescing operator</strong>&nbsp;(??) provides a default value when the object is null.<a rel="noreferrer noopener" target="_blank" href="https://www.c-sharpcorner.com/article/null-conditional-operators-in-c-sharp-simplifying-null-checks-more/"></a></p>



<br>



<h3 class="wp-block-heading" id="how-do-nullable-reference-types-help-prevent-null-reference-exception"><strong>How do nullable reference types help prevent NullReferenceException?</strong></h3>



<p class="custp1"><strong>Nullable reference types</strong>&nbsp;enable compile-time analysis that warns you about potential&nbsp;<strong>null reference issues</strong>&nbsp;before your code runs, allowing you to fix problems during development rather than at runtime.<a rel="noreferrer noopener" target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references"></a></p>



<br>



<h3 class="wp-block-heading" id="should-i-use-try-catch-to-handle-all-null-reference-exception"><strong>Should I use try-catch to handle all NullReferenceException?</strong></h3>



<p class="custp1">No,&nbsp;<strong>try-catch should not be your primary strategy</strong>.&nbsp;<strong>NullReferenceException</strong>&nbsp;typically indicates a programming error that should be fixed through proper&nbsp;<strong>null checking</strong>&nbsp;and defensive programming practices.<a rel="noreferrer noopener" target="_blank" href="https://dev.to/canro91/what-nullreferenceexception-is-and-how-to-avoid-it-2o35?comments_sort=latest"></a></p>



<br>



<br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="3,59,71">
<div id="latestPostlist"></div>
<br><br>


<figure class="wp-block-post-featured-image"><img fetchpriority="high" decoding="async" width="814" height="335" src="https://www.codeindotnet.com/wp-content/uploads/2025/09/what-is-nullreferenceexception-complete-guide-fixing-preventing.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="What is NullReferenceException? Complete Guide to Understanding, Fixing, and Preventing Null Reference Errors in C#" style="object-fit:cover;" srcset="https://www.codeindotnet.com/wp-content/uploads/2025/09/what-is-nullreferenceexception-complete-guide-fixing-preventing.jpg 814w, https://www.codeindotnet.com/wp-content/uploads/2025/09/what-is-nullreferenceexception-complete-guide-fixing-preventing-300x123.jpg 300w, https://www.codeindotnet.com/wp-content/uploads/2025/09/what-is-nullreferenceexception-complete-guide-fixing-preventing-768x316.jpg 768w" sizes="(max-width: 814px) 100vw, 814px" /></figure>


<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#what-is-nullreferenceexception">What is NullReferenceException?</a></li><li><a href="#how-to-fix-nullreferenceexception">How to Fix NullReferenceException</a><ul><li><a href="#step-1-identify-the-exact-location">1. Identify the Exact Location</a></li><li><a href="#step-2-use-debugging-tools">2. Use Debugging Tools</a></li><li><a href="#step-3-implement-null-checks">3. Implement Null Checks</a></li><li><a href="#step-4-use-safe-navigation-patterns">4. Use Safe Navigation Patterns</a></li><li><a href="#step-5-provide-default-values">5. Provide Default Values</a></li></ul></li><li><a href="#advanced-debugging-techniques">Advanced Debugging Techniques</a><ul><li><a href="#using-debug-assert-for-development">1. Using Debug.Assert for Development</a></li><li><a href="#exception-handling-with-try-catch">2. Exception Handling with Try-Catch</a></li><li><a href="#using-nullable-reference-types">3. Using Nullable Reference Types</a></li></ul></li><li><a href="#ways-to-prevent-nullreferenceexception">Ways to Prevent NullReferenceException</a><ul><li><a href="#1-defensive-programming">1. Defensive Programming</a></li><li><a href="#2-initialize-variables-properly">2. Initialize Variables Properly</a></li><li><a href="#3-use-constructor-injection">3. Use Constructor Injection</a></li><li><a href="#4-implement-null-object-pattern">4. Implement Null Object Pattern</a></li><li><a href="#5-use-guard-clauses">5. Use Guard Clauses</a></li><li><a href="#6-enable-nullable-reference-types">6. Enable Nullable Reference Types</a></li><li><a href="#7-use-modern-c-features">7. Use Modern C# Features</a></li></ul></li><li><a href="#debugging-tools-and-techniques">Debugging Tools and Techniques</a><ul><li><a href="#visual-studio-debugging-features">1. Visual Studio Debugging Features</a></li><li><a href="#unity-specific-debugging">2. Unity-Specific Debugging</a></li><li><a href="#logging-and-monitoring">3. Logging and Monitoring</a></li></ul></li><li><a href="#best-practices-summary">Best Practices Summary</a></li><li><a href="#conclusion">Conclusion</a></li><li><a href="#frequently-asked-questions-faqs">Frequently Asked Questions (FAQs)</a><ul><li><a href="#what-does-object-reference-not-set-to-an-instance-of-an-object-mean">What does &#8220;Object reference not set to an instance of an object&#8221; mean?</a></li><li><a href="#how-do-i-find-which-object-is-null-in-a-method-chain">How do I find which object is null in a method chain?</a></li><li><a href="#can-null-reference-exception-be-caught-and-handled">Can NullReferenceException be caught and handled?</a></li><li><a href="#whats-the-difference-between-null-conditional-operator-and-null-coalescing-operator">What&#8217;s the difference between null-conditional operator and null-coalescing operator?</a></li><li><a href="#how-do-nullable-reference-types-help-prevent-null-reference-exception">How do nullable reference types help prevent NullReferenceException?</a></li><li><a href="#should-i-use-try-catch-to-handle-all-null-reference-exception">Should I use try-catch to handle all NullReferenceException?</a></li></ul></li></ul></nav></div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/what-is-nullreferenceexception-complete-guide-fixing-preventing/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Read Excel Cell Values using Open XML in C# .Net Core</title>
		<link>https://www.codeindotnet.com/read-excel-cell-value-from-openxml-net-core-c/</link>
					<comments>https://www.codeindotnet.com/read-excel-cell-value-from-openxml-net-core-c/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 21 Nov 2023 15:46:09 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[documentformat.openxml]]></category>
		<category><![CDATA[import excel to datatable openxml c#]]></category>
		<category><![CDATA[openxml excel c#]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=6164</guid>

					<description><![CDATA[C# .NET Core provides a robust platform for building applications that interact with Excel files making it easy to read Excel sheet&#8217;s cell value of any column type. Open XML is an open standard file format for office applications, maintained by the International Organization for Standardization (ISO). It is the default file format for Microsoft [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<p>C# .NET Core provides a robust platform for building applications that interact with Excel files making it easy to read Excel sheet&#8217;s cell value of any column type.  Open XML is an open standard file format for office applications, maintained by the International Organization for Standardization (ISO). It is the default file format for Microsoft Office documents, including Excel (.xlsx) files. Open XML provides a structured way to represent document content, making it possible to interact with the various elements within an Office document programmatically. In this article, we will understand the process of reading Excel cell values using Open XML in a C# .NET Core application.</p>



<h2 class="wp-block-heading" id="step-by-step-guide-to-read-excel-spreadsheet-cell-values-from-open-xml-in-c">Step-by-step Guide to Read Excel Spreadsheet Cell Values from OpenXML in C# </h2>



<br>



<p>For demonstration purposes, we&#8217;re going to use a Web API to upload an Excel file. So before we begin, let&#8217;s ensure that you have a C# .NET Core project set up. Then, we&#8217;ll use the OpenXML package to read Excel sheet &amp; its values in each cell and store them in a DataTable.</p>



<br>



<h3 class="wp-block-heading hLBRed" id="install-open-xml-sdk-nuget-package"><strong>Install OpenXml SDK Nuget Package</strong></h3>



<br>



<p>Install an <a href="https://github.com/dotnet/Open-XML-SDK" target="_blank" rel="noopener"><strong>OpenXML</strong></a> Nuget Package into the Web API project, using either:</p>



<div><b><i><u>NuGet Package Manager:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/readexcel/documentformat-openxml-nuget-package-manager.jpg" alt=""/></figure>



<p class="custp1"><strong>Or</strong></p>



<div><b><i><u>Package Manager Console:</u></i></b></div>



<p class="has-white-color has-black-background-color has-text-color has-background"><strong><mark style="background-color:#000000" class="has-inline-color has-white-color">PM&gt;   Install-Package DocumentFormat.OpenXml -Version 3.0.0</mark></strong></p>



<br><br>



<p>After you install the package, you can include these assembly directives to use OpenXML, in the <strong>&#8216;Controller.cs&#8217;</strong> class.</p>



<div><b><i><u>Namespaces:</u></i></b></div>



<button class="c-b-s-f-r" onclick="ctc('div1',this)">Copy code</button>
<br>
<div id="div1">
<pre class="pchl"><code><span class="key">using</span> DocumentFormat.OpenXml.Packaging;
<span class="key">using</span> DocumentFormat.OpenXml.Spreadsheet;</code></pre>
</div>



<br><br><br>



<h3 class="wp-block-heading hLBRed" id="create-api-to-get-an-excel-file"><strong>Create API to get an Excel file</strong></h3>



<br>



<p>Create an HTTP POST method in the controller class to receive the uploaded file from the API.</p>



<button class="c-b-s-f-r" onclick="ctc('div2',this)">Copy code</button>
<br>
<div id="div2">
<pre class="pchl"><code>&#91;<span class="custkey">HttpPost</span>(<span class="str">"UploadExcelFile"</span>)]
<span class="key">public</span> <span class="custkey">IActionResult</span> UploadExcelSheet(<span class="custkey">IFormFile</span> uploadRegistration)
{
	<span class="key">string</span> fileName = uploadRegistration.FileName;

	<span class="custkey">DataTable</span> dt = ConvertExcelToDataTable(uploadRegistration);

	<span class="com">// write your logic,</span>
	<span class="com">// example insert DataTable result into Database</span>

	<span class="key">return</span> Ok();
}</code></pre>
</div>



<br>



<p>The API takes <span class="spanHT">IFormFile</span> as a parameter, representing a file sent with the HttpRequest. </p>



<br><br><br>



<h3 class="wp-block-heading hLBRed" id="read-data-from-excel-sheet-using-open-xml-c"><strong>Read Data from Excel Sheet using OpenXML &#8211; C#</strong></h3>



<br>



<button class="c-b-s-f-r" onclick="ctc('div3',this)">Copy code</button>
<br>
<div id="div3">
<pre class="pchl"><code><span class="key">private</span> <span class="custkey">DataTable</span> ConvertExcelToDataTable(<span class="custkey">IFormFile</span> uploadRegistration)
{
	<span class="com">//Create a new DataTable.</span>
	<span class="custkey">DataTable</span> dt = new <span class="key">DataTable</span>();
	dt.Columns.Add(<span class="str">"FIRST_NAME"</span>, <span class="key">typeof</span>(<span class="key">string</span>));
	dt.Columns.Add(<span class="str">"LAST_NAME"</span>, <span class="key">typeof</span>(<span class="key">string</span>));
	dt.Columns.Add(<span class="str">"PHONE_NUMBER"</span>, <span class="key">typeof</span>(<span class="key">int</span>));
	dt.Columns.Add(<span class="str">"EMAIL"</span>, <span class="key">typeof</span>(<span class="key">string</span>));
	dt.Columns.Add(<span class="str">"ADDRESS"</span>, <span class="key">typeof</span>(<span class="key">string</span>));

	<span class="key">using</span> (<span class="custkey">SpreadsheetDocument</span> doc = <span class="custkey">SpreadsheetDocument</span>.Open(uploadRegistration.OpenReadStream(), <span class="key">false</span>))
	{
		<span class="com">//Read the first Sheet from Excel file.</span>
		<span class="custkey">Sheet</span> sheet = doc.WorkbookPart.Workbook.Sheets.GetFirstChild&lt;<span class="custkey">Sheet</span>>();

		<span class="com">//Get the Worksheet instance.</span>
		<span class="custkey">Worksheet</span> worksheet = (doc.WorkbookPart.GetPartById(sheet.Id.Value) as <span class="custkey">WorksheetPart</span>).Worksheet;

		<span class="com">//Fetch all the rows present in the Worksheet.</span>
		<span class="custkey">IEnumerable</span>&lt;<span class="custkey">Row</span>> rows = worksheet.GetFirstChild&lt;<span class="custkey">SheetData</span>>().Descendants&lt;<span class="custkey">Row</span>>();

		<span class="com">//Loop through the Worksheet rows.</span>
		<span class="key">foreach</span> (<span class="custkey">Row</span> row in rows)
		{
			<span class="com">//If first row is header and you want to use same excel header name in Database column.</span>
			<span class="custkey">if</span> (row.RowIndex.Value == 1)
			{
				<span class="com">//foreach (Cell cell in row.Descendants&lt;Cell>())</span>
				<span class="com">//{</span>
				<span class="com">//    dt.Columns.Add(GetCellValue(doc, cell));</span>
				<span class="com">//}</span>
			}
			<span class="custkey">else</span>
			{
				<span class="key">string</span> firstName = GetCellValue(doc, (Cell)row.ElementAt(0));
				<span class="key">string</span> lastName = GetCellValue(doc, (Cell)row.ElementAt(1));

				<span class="custkey">DataRow</span> dataRow = dt.NewRow();

				<span class="com">// Validate if empty</span>
				<span class="key">if</span> (!<span class="key">string</span>.IsNullOrEmpty(firstName))
				{
					dataRow&#91;<span class="str">"FIRST_NAME"</span>] = firstName.Trim();
				}

				<span class="key">if</span> (!<span class="key">string</span>.IsNullOrEmpty(lastName))
				{
					dataRow&#91;<span class="str">"LAST_NAME"</span>] = lastName.Trim();
				}

				dataRow&#91;<span class="str">"PHONE_NUMBER"</span>] = GetCellValue(doc, (<span class="custkey">Cell</span>)row.ElementAt(2)).Trim();

				dataRow&#91;<span class="str">"EMAIL"</span>] = GetCellValue(doc, (<span class="custkey">Cell</span>)row.ElementAt(3)).Trim();

				dataRow&#91;<span class="str">"ADDRESS"</span>] = GetCellValue(doc, (<span class="custkey">Cell</span>)row.ElementAt(4)).Trim();

				dt.Rows.Add(dataRow);
			}
		}

	}

	<span class="key">return</span> dt;
}


<span class="key">private string</span> GetCellValue(<span class="custkey">SpreadsheetDocument</span> doc, <span class="custkey">Cell</span> cell)
{
	if (cell.CellValue != <span class="key">null</span>)
	{
		<span class="key">string</span> value = cell.CellValue.InnerText;
		if (cell.DataType != <span class="key">null</span> &amp;&amp; cell.DataType.Value == <span class="custkey">CellValues</span>.SharedString)
		{
			<span class="com">// in older version e.g. 2.0, you can use <span style="background:#f2f19d;">GetItem</span> instead of <span style="background:#f2f19d;">ElementAt</span></span>
			<span class="key">return</span> doc.WorkbookPart.SharedStringTablePart.SharedStringTable.ChildElements.<b>ElementAt</b>(<span class="key">int</span>.Parse(value)).InnerText;
		}
		else
		{
			<span class="key">return</span> value;
		}
	}
	<span class="key">return string</span>.Empty;
}</code></pre>
</div>



<br><div>In this code:</div>



<ol class="wp-block-list">
<li>We open the Excel file (<strong>RegistrationFormTest.xlsx</strong> in this case) using the <strong>SpreadsheetDocument.Open</strong> method.</li>



<li>We obtain the <strong>WorkbookPart </strong>and identify the first sheet in the workbook.</li>



<li>For each row in the sheet, we iterate through the cells, using the <strong>GetCellValue</strong> method to retrieve the cell value.</li>



<li>The <strong>GetCellValue</strong> method takes care of differentiating between shared string values and other types of cell values. It reads Excel Sheet cell value and stores the result in the DataTable.</li>
</ol>



<br>



<p class="brgrey"><strong><em><mark style="background-color:rgba(0, 0, 0, 0);color:#00008b" class="has-inline-color">also read:</mark></em></strong> <a href="/export-dataset-to-excel-in-c-net-core-openxml/" data-type="post" data-id="1880"><span class="cLink3"><strong>How to Export DataSet To Excel in C# .Net Core &#8211; OpenXml</strong></span></a></p>



<br><br>



<h3 class="wp-block-heading hLBRed" id="testing-upload-read-excel-file">Testing &#8211; Upload &amp; Read Excel file</h3>



<br>



<p>Let&#8217;s consider an example. I have a basic Excel file with the column and row information. Now, let&#8217;s attempt to upload and read the file using API, as shown in the screenshots below.</p>



<br>



<p class="hLBRed"><strong>Screenshots:</strong></p>



<div><b><i><u>sample excel file (RegistrationFormTest.xlsx)</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/readexcel/excel-sample-data-to-read-from-csharp.jpg" alt=""/></figure>



<br><br><div><b><i><u>upload excel file</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/readexcel/upload-excel-file-via-post-api.jpg" alt=""/></figure>



<br><br><div><b><i><u>get file via api</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/readexcel/read-excel-iformfile-debug.jpg" alt=""/></figure>



<br><br><div><b><i><u>read cell value</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/readexcel/openxml-get-cell-value-by-column-name.jpg" alt="openxml get cell value by column name"/></figure>



<br><br><div><b><i><u>output stored in Datatable</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/readexcel/read-excel-file-datatable-result-visualizer.jpg" alt=""/></figure>



<br>



<p>In this example, we demonstrate how to read Excel spreadsheet cell values and add results to the DataTable. However, you also have the option to save all records to a database. This can be done either through bulk insert or by saving each row individually, passing the values of each row via the property object.</p>



<br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Download &#038; Try Yourself:</div>
<div class="notepoints" style="padding-top:0.375rem">Read Excel File, .Net Core Web API <b>Source code</b> (<b>VS 2022</b>) &#8211; <a href="/img/1/readexcel/ReadExcel.zip"><span class="cLink3"><b>Download</b></span></a></div>
<div class="notepoints">Sample Excel File (RegistrationFormTest.xlsx) &#8211; <a href="/img/1/readexcel/RegistrationFormTest.xlsx"><span class="cLink3"><b>Download</b></span></a></div>
</div>



<div id="PageInAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="3,59,71">
<div id="latestPostlist"></div>
<br>



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#step-by-step-guide-to-read-excel-spreadsheet-cell-values-from-open-xml-in-c">Step-by-step Guide to Read Excel Spreadsheet Cell Values from OpenXML in C# </a><ul><li><a href="#install-open-xml-sdk-nuget-package">Install OpenXml SDK Nuget Package</a></li><li><a href="#create-api-to-get-an-excel-file">Create API to get an Excel file</a></li><li><a href="#read-data-from-excel-sheet-using-open-xml-c">Read Data from Excel Sheet using OpenXML &#8211; C#</a></li><li><a href="#testing-upload-read-excel-file">Testing &#8211; Upload &amp; Read Excel file</a></li></ul></li></ul></nav></div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/read-excel-cell-value-from-openxml-net-core-c/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Create Custom Exception Filter in .Net Core C#?</title>
		<link>https://www.codeindotnet.com/create-custom-exception-filter-attribute-handler-class/</link>
					<comments>https://www.codeindotnet.com/create-custom-exception-filter-attribute-handler-class/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 04 Oct 2023 19:33:51 +0000</pubDate>
				<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[exceptionfilterattribute .net core web api C#]]></category>
		<category><![CDATA[override OnExceptionAsync]]></category>
		<category><![CDATA[return user-friendly error message in response body]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5547</guid>

					<description><![CDATA[.NET provides a hierarchy of built-in exception classes that are derived from the fundamental Exception base class. However, there may be times when none of the predefined exceptions meet your specific needs or requirements. In such case, you can create your own exception classes by deriving from the Exception class. In this article, we will [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<p class="custp1">.NET provides a hierarchy of built-in exception classes that are derived from the fundamental Exception base class. However, there may be times when none of the predefined exceptions meet your specific needs or requirements. In such case, you can create your own exception classes by deriving from the Exception class. In this article, we will discuss how to create custom exceptions in .Net Core using <span class="spanHT">ExceptionFilterAttribute</span> and implementing a global exception-handling mechanism in the Web API .Net Core application.</p>



<br>



<div class="noteimpwar">
<div style="color:#dc2323; font-weight:bold; font-style:italic;"><span style="border-bottom:0.125rem #dc2323 solid;">Scenario/ requirement:</span></div>
<div style="padding-top:0.575rem; margin-left: 2em;">
Write a common global exception error handling mechanism that is capable of capturing error details. Achieve the following:<br> <strong>&#8211;</strong> An error might occur at any layer(API method, business, data access layers) in the application during the execution of a web API method and all those errors should be captured by a single exception filter class, <br> <strong>&#8211;</strong> capture &amp; log requested API (URL path), error message &amp; full stack trace,<br> <strong>&#8211;</strong> return a custom user-friendly message in response body, <br> <strong>&#8211;</strong> should not use old-fashioned try-catch blocks in any method.
</div>
</div>



<br>



<h2 class="wp-block-heading" id="what-is-exception-filter-attribute"><strong>What is ExceptionFilterAttribute?</strong></h2>



<p class="custp1">In .NET Core, <span class="spanHT">ExceptionFilterAttribute</span> is a class that allows developers to create custom exception filters. Exception filters are used to handle exceptions that occur during the execution of ASP.NET Core MVC or Web API actions. These filters can be applied globally to all actions or selectively to specific controllers or actions. When an exception is thrown, an <strong><a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.exceptionfilterattribute" target="_blank" rel="noreferrer noopener">ExceptionFilterAttribute </a></strong>can catch it, perform custom logic (such as logging or generating a specific response), and potentially prevent the exception from propagating to the higher levels of the application. This helps in creating more robust and user-friendly error handling mechanisms in .NET Core applications. In other words, ExceptionFilterAttribute is an attribute used to define exception filters in ASP.NET Web API.</p>



<div class="note">
<div style="padding-top:0.375rem"><strong><span style="color:#1e90ff; font-style: italic;">also read:</span></strong> Difference between <a href="/exceptionlogger-vs-exceptionfilter-vs-exceptionhandler-in-net-core" data-type="URL" data-id="/exceptionlogger-vs-exceptionfilter-vs-exceptionhandler-in-net-core" target="_blank" rel="noopener"><strong><span class="cLink3">ExceptionLogger vs. ExceptionFilter vs. ExceptionHandler</span></strong></a> in .NET Core</div>
</div>



<br><br><br>



<h2 class="wp-block-heading h2Cust1" id="create-an-exception-filter-class-and-override-the-on-exception-method"><strong>Create an Exception Filter class and override the OnException Method</strong></h2>



<p class="custp1">The implementation for creating a custom Exception Filter is done in the following 3 simple steps.</p>



<h3 class="wp-block-heading hLBRed" id="step-1-create-custom-exception-class"><strong>Step 1: Create Custom Exception Class </strong></h3>



<p class="custp1">To address unhandled exception scenarios, you can create a custom exception filter by defining a class that inherits the ExceptionFilterAttribute abstract class which implements the IExceptionFilter interface internally. In our example, we have given the class name as CustomExceptionAttribute.<br><strong><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Note:</mark></em></strong> End the class name with <span class="spanHT">Arrtibute</span>.</p>



<p><strong><em><span style="text-decoration: underline;">Custom Exception Filter Class</span></em></strong></p>



<button class="c-b-s-f-r" onclick="ctc('div1',this)">Copy code</button>
<br>
<div id="div1">
<pre class="pchl"><code>
<span class="key">using</span> System.Threading.Tasks;
<span class="key">using</span> Microsoft.AspNetCore.Mvc;
<span class="key">using</span> Microsoft.AspNetCore.Mvc.Filters;
<span class="key">using</span> Microsoft.Extensions.Logging;

<span class="key">namespace</span> Product.Web
{
    <span class="key">public</span> <span class="key">class</span> <span class="custkey"><span class="custkey">CustomExceptionAttribute</span></span> : <span class="custkey" style="background:#fafbbb;"><b>ExceptionFilterAttribute</b></span>
    {
        <span class="key">private</span> <span class="key">readonly</span> <span class="custkey">ILogger</span> _logger;

        <span class="com">//constructor</span>
        <span class="key">public</span> <span class="custkey"><span class="custkey">CustomExceptionAttribute</span></span>(<span class="custkey">ILogger</span> logger)
        {
            _logger = logger;
        }


        <span class="com">// override the OnException Method</span>
        <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnException(<span class="custkey"><span class="custkey">ExceptionContext</span></span> ex)
        {
            <span class="key">var</span> controllerActionDescriptor = ((Microsoft.AspNetCore.Mvc.Controllers.<span class="custkey">ControllerActionDescriptor</span>)ex.ActionDescriptor);

            _logger.LogError(<span class="str">"API: "</span> + controllerActionDescriptor.AttributeRouteInfo.Template + <span class="str">"\r\n"</span>
                    + ex.Exception.Message + <span class="str">"\r\n"</span>
                    + ex.Exception.ToString());

            <span class="custkey">//assigning custom response</span>
            ex.Result = JsonResultDto();

            ex.HttpContext.Response.StatusCode = 400;  
        }


        <span class="com">// override the OnException <b>async</b> Method </span>
        <span class="key">public</span> <span class="key">override</span> <span class="key">async</span> <span class="custkey">Task</span> OnExceptionAsync(<span class="custkey"><span class="custkey">ExceptionContext</span></span> ex)
        {
            <span class="key">var</span> controllerActionDescriptor = ((Microsoft.AspNetCore.Mvc.Controllers.<span class="custkey">ControllerActionDescriptor</span>)ex.ActionDescriptor);
                
            _logger.LogError(<span class="str">"API: "</span> + controllerActionDescriptor.AttributeRouteInfo.Template + <span class="str">"\r\n"</span>
                    + ex.Exception.Message + <span class="str">"\r\n"</span>
                    + ex.Exception.ToString());

            <span class="key">await</span> <span class="custkey">Task</span>.FromResult(0);

            <span class="custkey">//assigning custom response</span>
            ex.Result = JsonResultDto();

            ex.HttpContext.Response.StatusCode = 400;
        }

        <span class="com">// returning custom Json response</span>
        <span class="key">private</span> <span class="custkey">JsonResult</span> JsonResultDto()
        {
            <span class="key">return</span> <span class="key">new</span> <span class="custkey">JsonResult</span>(
                <span class="key">new</span>
                {
                    ErrorMessage = <span class="str">"Internal error occurred."</span>,
                    HasError = <span class="key">true</span>,
                    ResponseCode = 400
                });

        }
    }
} </code></pre>
</div>



<p>In the above code, we have overridden two OnException methods (one for normal and another for async methods). If any exception occurs while executing an API method (or in its internal sub-methods) then the code will hit the custom exception filter class. The OnException method will be invoked depending on whether the call is synchronous or asynchronous. <br>Here, we are using the ILogger interface to log the error details such as: <br>1) API Path, <br>2) Exception message, <br>3) full error stack trace.</p>



<p>The benefit of an Exception Filter is we can return a user-friendly error message to the front-end application in the response body. In the example, after logging the error, the <strong>JsonResultDto()</strong> method is called which will return the user-defined Json result to the user.</p>



<br><br>



<h3 class="wp-block-heading hLBRed" id="step-2-registering-exception-filter"><strong>Step 2: Registering Exception Filter</strong></h3>



<p class="custp1">We need to define the scope and register the custom exception filter globally, inside the <strong>ConfigureServices </strong>method in the <strong>startup.cs</strong> file.</p>



<p>Add <span class="spanHT">services.AddScoped&lt;CustomExceptionAttribute&gt;();</span> line of code as shown below:</p>



<button class="c-b-s-f-r" onclick="ctc('div2',this)">Copy code</button>
<br>
<div id="div2">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span class="custkey">Startup</span>
{
	<span class="key">public</span> <span class="key">void</span> ConfigureServices(<span class="custkey">IServiceCollection</span> services)
	{
		<span class="com">//...</span>
		<span class="com">//services.AddControllers();</span>
		<span class="com">//...</span>
		
		<span class="com">//register CustomExceptionAttribute class</span>
		<b><span style="background:#fafbbb;">services.AddScoped&lt;<span class="custkey">CustomExceptionAttribute</span>&gt;();</span></b>
	}
} </code></pre>
</div>



<br><br>



<h3 class="wp-block-heading hLBRed" id="step-3-apply-exception-filter-on-controller-or-action-methods"><strong>Step 3: Apply Exception Filter on Controller or Action methods</strong></h3>



<p class="custp1">To use a registered filter, it should be placed or decorated at the top of the Controller or Action as a ServiceType.</p>



<p>You can apply the Exception Filter at: <br>1) Controller Level, or<br>2) Action Level (one or more based on your requirement).</p>



<p>The example shows custom exception filter is applied at the Controller level, which means it is applicable to all API methods as well. <br>The <span class="spanHT">GetProducts()</span> method will throw <span class="spanHT">System.FormatException</span> error when code tries to convert a string variable (object) to an integer.</p>



<p>Add <span class="spanHT">[ServiceFilter(typeof(CustomExceptionAttribute))]</span> line of code above the Controller class, as shown below:</p>



<button class="c-b-s-f-r" onclick="ctc('div3',this)">Copy code</button>
<br>
<div id="div3">
<pre class="pchl"><code><span class="key">namespace</span> Product.Web
{
    <span style="background:#fafbbb; font-weight:bold;">[<span class="custkey">ServiceFilter</span>(<span class="key">typeof</span>(<span class="custkey"><span class="custkey">CustomExceptionAttribute</span></span>))]</span>
    [<span class="custkey">ApiController</span>]
    [<span class="custkey">Route</span>(<span class="str">"[controller]"</span>)]
    <span class="key">public</span> <span class="key">class</span> <span class="custkey">ProductController</span>
    {
	
        [<span class="custkey">HttpGet</span>]
        [<span class="custkey">Route</span>(<span class="str">"GetProducts"</span>)]
        <span class="key">public</span> <span class="custkey">IActionResult</span> GetProducts()
        {
            <span class="com">//example: System.FormatException: 'Input string was not in a correct format.'</span>
            <span class="key">object</span> input = <span class="com">"test"</span>;
            <span class="key">int</span> result = <span class="custkey">Convert</span>.ToInt32(input);

            return Ok();
        }
	}
} </code></pre>
</div>



<br><br>



<h3 class="wp-block-heading hLBRed" id="testing-exception-filter-attribute-screenshots"><strong>Testing <strong>ExceptionFilterAttribute</strong> &#8211; Screenshots</strong></h3>



<p class="custp1">That&#8217;s it, now we can do a unit test and confirm if it is working as expected.</p>



<h4 class="wp-block-heading" id="swagger-api-test"><strong><span style="text-decoration: underline;"><em>Swagger API Test</em></span></strong></h4>



<p class="custp1">Call &amp; execute API method from <strong>Swagger</strong>. It will return &#8220;<strong>400 &#8211; Bad Request</strong>&#8221; with a user-friendly JSON message in the response body, as shown in the below screenshot.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/custom-exception-filter-attribute-user-friendly-error-message.jpg" alt="custom exception filter attributeuser friendly error message"/></figure>



<br><br>



<h4 class="wp-block-heading" id="debug-code"><strong><em><span style="text-decoration: underline;">Debug code</span></em></strong></h4>



<p class="custp1">The custom exception class will be called whenever an error occurs in the Controller&#8217;s Web API method and it will capture &amp; log the following details: <br>1) on which API error occurred e.g., Path: &#8220;Product/GetProducts&#8221;<br>2) error message e.g., &#8220;Input string was not in a correct format.&#8221;<br>3) full stack trace</p>



<p>see the debugging screenshot below.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/custom-exception-filter-attribute-debug-error-message.jpg" alt="custom exception filter attribute debug error message.jpg"/></figure>



<div id="PageInAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br><br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="3,59,71">
<div id="latestPostlist"></div>



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#what-is-exception-filter-attribute">What is ExceptionFilterAttribute?</a></li><li><a href="#create-an-exception-filter-class-and-override-the-on-exception-method">Create an Exception Filter class and override the OnException Method</a><ul><li><a href="#step-1-create-custom-exception-class">Step 1: Create Custom Exception Class </a></li><li><a href="#step-2-registering-exception-filter">Step 2: Registering Exception Filter</a></li><li><a href="#step-3-apply-exception-filter-on-controller-or-action-methods">Step 3: Apply Exception Filter on Controller or Action methods</a></li><li><a href="#testing-exception-filter-attribute-screenshots">Testing ExceptionFilterAttribute &#8211; Screenshots</a><ul><li><a href="#swagger-api-test">Swagger API Test</a></li><li><a href="#debug-code">Debug code</a></li></ul></li></ul></li></ul></nav></div>



<style>
.toc-cust{
border:1px solid #add8e6;
padding-top: 15px;
padding-left:15px;
}
.toc-cust h2{
font-weight:bold;
font-size: 1.5rem;
color:#ba3925e3;
}
</style>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/create-custom-exception-filter-attribute-handler-class/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Difference between ExceptionLogger vs. ExceptionFilter vs. ExceptionHandler in .NET Core</title>
		<link>https://www.codeindotnet.com/exceptionlogger-vs-exceptionfilter-vs-exceptionhandler-in-net-core/</link>
					<comments>https://www.codeindotnet.com/exceptionlogger-vs-exceptionfilter-vs-exceptionhandler-in-net-core/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 04 Oct 2023 19:32:52 +0000</pubDate>
				<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[purpose scope of exception]]></category>
		<category><![CDATA[when to use exception]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5531</guid>

					<description><![CDATA[We will understand the difference between ExceptionLogger, ExceptionFilter, and ExceptionHandler which helps to handle exceptions in several ways in .NET Core. In this article, we will explore each of these techniques, discussing when and how to use them with real-world examples. Difference &#8211; Overview Exception loggers Exception filters Exception handlers Exception loggers are the solution [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<p>We will understand the difference between ExceptionLogger, ExceptionFilter, and ExceptionHandler which helps to handle exceptions in several ways in .NET Core. In this article, we will explore each of these techniques, discussing when and how to use them with real-world examples.</p>



<br>



<h2 class="wp-block-heading hLBRed"><strong>Difference &#8211; Overview</strong></h2>



<br>



<table>
    <thead>
        <tr>
            <th>Exception loggers</th>
            <th>Exception filters</th>
            <th>Exception handlers</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Exception loggers are the solution to seeing all unhandled exception caught by Web API.</td>
            <td>Exception filters are the easiest solution for processing the subset unhandled exceptions related to a specific action or controller.</td>
            <td>Exception handlers are the solution for customizing all possible responses to unhandled exceptions caught by Web API.</td>
        </tr>
    </tbody>
</table>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>ExceptionLogger</strong></h2>



<p class="custp1">ExceptionLogger allows you to log exceptions that occur during the <strong>execution of your application</strong>. It provides a way to capture detailed information about exceptions, such as the exception message, stack trace, and other relevant data, and then log this information using a custom logging mechanism.</p>



<p>ExceptionLogger is typically used for auditing and monitoring purposes. It helps developers and administrators track the occurrence of exceptions in an application, enabling them to diagnose issues, identify error patterns, and take corrective actions.</p>



<h3 class="wp-block-heading"><strong>When to use ExceptionLogger:</strong></h3>



<p class="custp1">You might use an ExceptionLogger to log exceptions to a central log database or send alerts to a monitoring system like Application Insights or ELK Stack. <br>Use ExceptionLogger when you want to log exceptions that occur during the execution of your application. ExceptionLogger allows you to capture detailed information about exceptions, including the exception message, stack trace, and other relevant data.</p>



<p><strong><em>Purpose:</em></strong> all unhandled exceptions (before they even reach exception filters) <br><strong><span style="text-decoration: underline;"><em>Scope:</em></span></strong> global</p>



<pre class="pchl"><code><span class="key">public class</span> CustomExceptionLogger : <span class="custkey">ExceptionLogger</span>
{
    <span class="key">public override void</span> Log(ExceptionLoggerContext context)
    {
        <span class="com">// Log the exception details using your preferred logging mechanism</span>
        LogHelper.LogException(context.Exception);
    }
}
</code></pre>



<p>In this example, we create a custom ExceptionLogger that logs exceptions using a custom logging utility. You can then register this logger in your application&#8217;s configuration to handle exception logging.</p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>ExceptionFilter</strong></h2>



<p class="custp1">ExceptionFilter allows you to perform <strong>custom actions in response to specific exceptions</strong> during the execution of your application. It lets you modify the HTTP response, redirect the user, or execute any other logic based on the exception type or conditions you define.</p>



<p>ExceptionFilters are useful when you need to handle exceptions in a more fine-grained manner. You can use them to implement custom error handling behavior for specific scenarios. For example, you might want to return a <strong>user-friendly error message</strong> for a particular exception type or redirect the user to a login page if their session has expired.</p>



<h3 class="wp-block-heading"><strong>When to use ExceptionFilter:</strong></h3>



<p class="custp1">You can create an ExceptionFilter to catch and handle authorization-related exceptions by redirecting the user to a login page or returning a 403 Forbidden status code. <br>ExceptionFilters are useful when you need to perform custom actions in response to specific exceptions. They allow you to modify the HTTP response, redirect the user, or perform any other action based on the exception type or condition.</p>



<p><strong><em>Purpose:</em></strong> handle (not log) exceptions<br><strong><em>Scope:</em></strong> per action, per controller, global</p>



<pre class="pchl"><code><span class="key">public class</span> CustomExceptionFilter : <span class="custkey">IExceptionFilter</span>
{
    <span class="key">public void</span> OnException(ExceptionContext context)
    {
        <span class="key">if</span> (context.Exception <span class="key">is</span> CustomNotFoundException)
        {
            <span class="com">// Handle the not found exception by returning a custom response</span>
            context.Result = <span class="key">new</span> NotFoundObjectResult(<span class="com">"Resource not found</span>");
            context.ExceptionHandled = <span class="key">true</span>;
        }
    }
}
</code></pre>



<p>In this example, a CustomExceptionFilter is used to catch a specific CustomNotFoundException and return a custom response. You can register this filter globally or on specific controllers or action methods as needed.</p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>ExceptionHandler</strong></h2>



<p class="custp1">ExceptionHandler deals with<strong> unhandled exceptions</strong> that occur during the execution of your application. It provides a way to customize the behavior when an unhandled exception is encountered, such as redirecting the user to an error page, returning a specific response, or performing cleanup tasks.</p>



<p>ExceptionHandler is designed to handle exceptions that propagate beyond the scope of regular exception handling mechanisms like try-catch blocks. It ensures that your application gracefully manages unhandled exceptions, preventing crashes and providing a more user-friendly experience.</p>



<h3 class="wp-block-heading"><strong>When to use ExceptionHandler:</strong></h3>



<p class="custp1">You can configure an ExceptionHandler to catch unhandled exceptions and return a custom error response with a 500 Internal Server Error status code. This helps ensure that users receive a meaningful error message rather than seeing a generic server error page. <br>ExceptionHandler is suitable for handling unhandled exceptions that occur during the execution of your application. It allows you to customize the behavior when an unhandled exception occurs, such as redirecting the user to an error page or returning a specific response.</p>



<p><strong><em>Purpose:</em></strong> log and handle unpredictable/unexpected exceptions<br><strong><em>Scope:</em></strong> global</p>



<pre class="pchl"><code><span class="key">public class</span> CustomExceptionHandler : <span class="custkey">IExceptionHandler</span>
{
    <span class="key">public</span> Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        <span class="com">// Handle the exception and return a custom response</span>
        context.Result = <span class="key">new</span> ObjectResult(<span class="com">"An error occurred"</span>)
        {
            StatusCode = StatusCodes.Status500InternalServerError
        };
        <span class="key">return</span> Task.CompletedTask;
    }
}
</code></pre>



<p>In this example, a CustomExceptionHandler is used to catch unhandled exceptions and return a custom response with a 500 Internal Server Error status code. You can configure the ExceptionHandler in your application&#8217;s startup code to define how unhandled exceptions should be handled.</p>



<div id="PageInAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<p><strong>Conclusion</strong><br>Exception handling is a crucial part of any application&#8217;s development, and in .NET Core, you have several options to tailor your approach to your specific needs. ExceptionLogger, ExceptionFilter, and ExceptionHandler each serve distinct purposes, allowing you to log, filter, and handle exceptions effectively. </p>



<br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="3,59,71">
<div id="latestPostlist"></div>
<br>



<p><em><strong>reference:</strong></em> <a href="https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling" target="_blank" rel="noreferrer noopener">web-api-global-error-handling</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/exceptionlogger-vs-exceptionfilter-vs-exceptionhandler-in-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Validate Azure Active Directory B2C Jwt Bearer Token in .NET Core Web API &#8211; C#</title>
		<link>https://www.codeindotnet.com/validate-azure-active-directory-b2c-jwt-bearer-token/</link>
					<comments>https://www.codeindotnet.com/validate-azure-active-directory-b2c-jwt-bearer-token/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 11 Sep 2023 17:29:34 +0000</pubDate>
				<category><![CDATA[Web API]]></category>
		<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[azure b2c rest api]]></category>
		<category><![CDATA[AzureAdB2C]]></category>
		<category><![CDATA[b2c jwt .net core api]]></category>
		<category><![CDATA[Token Validation Parameters]]></category>
		<category><![CDATA[Validate IssuerSigning Key]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5058</guid>

					<description><![CDATA[To validate a JSON Web Token (JWT) issued by Azure Active Directory B2C (Azure AD B2C) in a .NET Core Web API, you need to configure the authentication middleware to validate the JWT tokens. Steps to Validate Azure AD B2C Jwt Bearer Create Web API project in .NET Core Install Required NuGet Packages Install the [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInAd1"></div>
<script>

fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<p class="custp1">To validate a JSON Web Token (JWT) issued by Azure Active Directory B2C (Azure AD B2C) in a .NET Core Web API, you need to configure the authentication middleware to validate the JWT tokens.</p>



<br>



<h2 class="wp-block-heading h2Cust1" id="steps-to-validate-azure-ad-b-2-c-jwt-bearer"><strong>Steps to Validate Azure AD B2C Jwt Bearer</strong></h2>



<br>



<p>Create Web API project in .NET Core</p>



<h3 class="wp-block-heading hLBRed" id="install-required-nu-get-packages"><strong>Install Required NuGet Packages</strong></h3>



<p class="custp1">Install the necessary <a href="https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer/" target="_blank" rel="noopener"><strong>JwtBearer NuGet packages</strong></a> to work with JWT authentication and Azure AD B2C.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="483" height="146" src="https://www.codeindotnet.com/wp-content/uploads/2023/09/microsoft-aspnetcore-authentication-jwtbearer-nuget.jpg" alt="microsoft aspnetcore authentication jwtbearer nuget validate b2c Azure token" class="wp-image-5066" srcset="https://www.codeindotnet.com/wp-content/uploads/2023/09/microsoft-aspnetcore-authentication-jwtbearer-nuget.jpg 483w, https://www.codeindotnet.com/wp-content/uploads/2023/09/microsoft-aspnetcore-authentication-jwtbearer-nuget-300x91.jpg 300w" sizes="(max-width: 483px) 100vw, 483px" /></figure>



<br><br>



<h3 class="wp-block-heading hLBRed" id="configure-azure-b-2-c-jwt-authentication"><strong>Configure Azure B2C JWT Authentication.</strong></h3>



<p class="custp1">In your <strong>Startup.cs</strong> file, configure JWT authentication in the <strong>ConfigureServices </strong>and <strong>Configure </strong>methods:</p>



<div><b><i><u>Startup.cs</u></i></b></div>



<pre class="pchl"><code><span class="key">using</span> Microsoft.AspNetCore.Authentication.JwtBearer;
<span class="key">using</span> Microsoft.IdentityModel.Tokens;
<span class="key">using</span> System.Text;

<span class="com">// ...</span>

<span class="key">public</span> <span class="key">void</span> ConfigureServices(<span class="custkey">IServiceCollection</span> services)
{
	<span class="com">// Add authentication services</span>
    services.AddAuthentication(<span class="custkey">JwtBearerDefaults</span>.AuthenticationScheme)
        .AddJwtBearer(options =&gt;
        {
			options.Authority = <span class="str">"AzureAdB2C:IssuerOrAuthorizationUrl"</span>;
			options.Audience = <span class="str">"AzureAdB2C:Audience"</span>;
			options.Events = <span class="key">new</span> <span class="custkey">JwtBearerEvents</span>
			{
				<span class="com">//OnAuthenticationFailed = AuthenticationFailed</span>
			};
			
			<span class="com">/* Note:Authority and audience are enough to validate AD B2C Authentication but if your requirement is to validate the Token issuer &amp; SigninKey also then include the below code as well.*/</span>
            options.<span class="custkey">TokenValidationParameters</span> = <span class="key">new</span> <span class="custkey">TokenValidationParameters</span>
            {
                ValidateIssuer = <span class="key">true</span>,
                ValidateAudience = <span class="key">true</span>,
                <span class="com">//ValidateLifetime = true,</span>
                ValidateIssuerSigningKey = <span class="key">true</span>,
                ValidIssuer = <span class="str">"AzureAdB2C:IssuerOrAuthorizationUrl"</span>,
                ValidAudience = <span class="str">"AzureAdB2C:Audience"</span>,
                IssuerSigningKey = <span class="key">new</span> SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[<span class="str">"AzureAdB2C:JwtKey"</span>]))
            };
        });

    <span class="com">// Other ConfigureServices configuration...</span>
}

<span class="key">public</span> <span class="key">void</span> Configure(<span class="custkey">IApplicationBuilder</span> app, <span class="custkey">IWebHostEnvironment</span> env)
{
    <span class="com">// Use authentication middleware</span>
    app.UseAuthentication();

    <span class="com">// Other Configure configuration...</span>
} </code></pre>



<br>



<div><b><i><u>appsettings.json</u></i></b></div>



<pre class="pchl"><code>{
  <span class="custkey">"AzureAdB2C"</span>: {
    <span class="custkey">"IssuerOrAuthorizationUrl"</span>: <span class="str">"https://&lt;your-tenant-name&gt;.b2clogin.com/&lt;your-tenant-name&gt;.onmicrosoft.com/&lt;your-policy-name&gt;/v2.0/"</span>,
    <span class="custkey">"Audience"</span>: <span class="str">"ecjud59-Your-ClientId-or-AudienceId-e0d02e"</span>,
    <span class="custkey">"JwtKey"</span>: <span class="str">"my_secret_key_12345"</span>
  }
}</code></pre>



<br><br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div style="padding-top:0.375rem">In my scenario, I had two web API apps for the same client, where in <br><b>app1:</b> &#8220;Authority &amp; Audience&#8221; was enough to validate B2C Authentication and <br><b>app2:</b> I used the &#8220;TokenValidationParameters&#8221; code to verify &#8220;IssuerSigningKey&#8221;. <br>So based on your requirement include or remove the lines of code.</div>
</div>



<br><br>



<h3 class="wp-block-heading hLBRed" id="authorize-api-endpoints"><strong>Authorize API Endpoints</strong></h3>



<p class="custp1">You can now protect your API endpoints by applying the <span class="spanHT">[Authorize]</span> attribute to the controllers or actions you want to secure:</p>



<pre class="pchl"><code><span class="key">using</span> Microsoft.AspNetCore.Authorization;

<span style="background:#f2f19d;">[<span class="custkey">Authorize</span>]</span>
[<span class="custkey">ApiController</span>]
[<span class="custkey">Route</span>("api/[controller]")]
<span class="key">public class</span> <span class="custkey">MyController</span> : <span class="custkey">ControllerBase</span>
{
    // Controller actions...
}
</code></pre>



<p>Your .NET Core rest API is now configured to validate JWT tokens issued by Azure AD B2C.</p>



<br>



<h3 class="wp-block-heading hLBRed" id="testing-azure-ad-b-2-c-jwt-bearer"><strong>Testing Azure AD B2C Jwt Bearer</strong></h3>



<p class="custp1">To test the JWT Bearer token authentication, include the JWT token in the <span class="spanHT">Authorization</span> header of your HTTP requests. The header should look like:</p>



<pre class="pchl"><code>Authorization: Bearer &lt;your-JWT-token&gt;
</code></pre>



<p>If validation is successful then it will execute the API method else app will throw an exception.</p>



<br>



<p>Make sure you have the correct Azure AD B2C configuration values in your application, and ensure that your B2C policies and user flows are set up to issue tokens with the required audience and issuer values.</p>



<p><em><strong>Handle Claims</strong>: </em>You can access user claims (e.g., user&#8217;s email, name, etc.) using <span class="spanHT">User.Claims</span> within your API controller actions.</p>



<div id="PageInAd2"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd2.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd2').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd2:', error);
	});
</script>



<br>



<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>popular readings:</i></b></span>
		<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
			<div><b>&#8211; <a href="https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/">How to Add Swagger in Web API .net core manually? &#8211; easy guide</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/send-calendar-invite-appointment-attachment/">[C#] calendar invite/appointment as email attachment (.net)</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/send-email-attachment-footer-meeting-invite/">[C#] Send email with attachment, footer &amp; calendar invite (.net)</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-integrate-mailchimp-v3-0-api-in-dotnet-core-c/">How to Integrate MailChimp v3.0 API in DotNet Core C#</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/jwt-bearer-token-authorization-in-swagger-api/">Test Web API with JWT Bearer Authentication In Swagger &#8211; .Net Core</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/export-dataset-to-excel-in-c-net-core-openxml/">Export DataSet To Excel in C# .Net Core &#8211; OpenXml</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-use-dynamic-parameters-in-dapper-2-0-in-c-net-core/">How To Use Dynamic Parameters In Dapper 2.0 In C# .Net Core?</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/sonarlint-code-clean-up-for-ms-visual-studio-cyclomatic-complexity-explained/">SonarLint Code Clean-up for MS Visual Studio &amp; Cyclomatic Complexity Explained</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/install-cloudflare-free-ssl-certificate-on-godaddy/">Configure free Cloudflare SSL certificate for Godaddy Shared Webhosting</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/create-wordpress-custom-plugin-in-3-steps/">How to Create Custom WordPress Plugin: 3 Easy Steps</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-create-mime-types-class-in-c-net-core/">How to Create MIME Types Custom Class in C#</a></b></div>

		</div>
	</div>
</div>



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#steps-to-validate-azure-ad-b-2-c-jwt-bearer">Steps to Validate Azure AD B2C Jwt Bearer</a><ul><li><a href="#install-required-nu-get-packages">Install Required NuGet Packages</a></li><li><a href="#configure-azure-b-2-c-jwt-authentication">Configure Azure B2C JWT Authentication.</a></li><li><a href="#authorize-api-endpoints">Authorize API Endpoints</a></li><li><a href="#testing-azure-ad-b-2-c-jwt-bearer">Testing Azure AD B2C Jwt Bearer</a></li></ul></li></ul></nav></div>



<style>
.toc-cust{
border:1px solid #add8e6;
padding-top: 15px;
padding-left:15px;
}
.toc-cust h2{
font-weight:bold;
font-size: 1.5rem;
color:#ba3925e3;
}
</style>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/validate-azure-active-directory-b2c-jwt-bearer-token/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Add Swagger in Web API .net core manually? &#8211; easy guide</title>
		<link>https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/</link>
					<comments>https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 09 Sep 2023 02:35:46 +0000</pubDate>
				<category><![CDATA[Web API]]></category>
		<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[add description to swagger api]]></category>
		<category><![CDATA[openapi]]></category>
		<category><![CDATA[swagger api docs]]></category>
		<category><![CDATA[swagger api documentation]]></category>
		<category><![CDATA[swagger api testing]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=4904</guid>

					<description><![CDATA[Swagger is a powerful tool for documenting and testing APIs in a user-friendly and interactive way. It allows developers to create interactive API documentation, making it easier for both developers and consumers to understand and interact with the API. While there are tools and packages that automate Swagger integration in .NET Core, sometimes you may [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInAd1"></div>
<script>

fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<p><a href="https://swagger.io/" target="_blank" rel="noopener"><strong>Swagger</strong></a> is a powerful tool for documenting and testing APIs in a user-friendly and interactive way. It allows developers to create interactive API documentation, making it easier for both developers and consumers to understand and interact with the API. While there are tools and packages that automate Swagger integration in .NET Core, sometimes you may want to implement it manually for more control over the configuration and customization. In this article, we will guide you through the manual implementation of Swagger in a .NET Core application.</p>



<br>



<h2 class="h2Cust1"><b>Swagger implementation in .NET Core Web API Project</b></h2>



<p class="custp1">The following steps describe the configuration of Swagger docs in the Web API project. </p>



<h3 class="wp-block-heading" id="step-1-install-required-packages"><strong>Step 1: Install Required Packages</strong></h3>



<p class="custp1">To begin, open your .NET Core project in Visual Studio or Visual Studio Code and <strong>install the necessary NuGet packages for Swagger</strong> integration. You need <span class="spanHT">Swashbuckle.AspNetCore</span> package. You can install these packages using the NuGet Package Manager or Package Manager Console:</p>



<h4 class="wp-block-heading" id="console-command"><strong><strong><em>option 1)</em></strong></strong> <strong><em><span style="text-decoration: underline;">Console Command</span></em></strong></h4>



<br>



<p class="custp1"><mark style="background-color:#000000; padding:20px; width=100%;" class="has-inline-color has-white-color">dotnet add package Swashbuckle.AspNetCore</mark></p>



<br>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/swagger/dotnet-add-package-swashbuckle-aspnetcore.jpg" alt="dotnet add package swashbuckle asp .net core"/></figure>



<br>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong>Note:</strong></mark> This command will add all packages available under Swashbuckle.AspNetCore. <br><strong>Recommendation</strong> &#8211; Install only necessary packages from Nuget Manager</p>



<br>



<h4 class="wp-block-heading" id="nuget-package-manager"><span><strong><em>option 2)</em></strong></span> <span><span style="font-weight: bold; font-style: italic; text-decoration: underline;">Nuget Package manager</span></span> <span style="background-color: #90ee90; padding: 0.0625rem 0.3125rem; border-radius:0.625rem">recommended</span></h4>



<p class="custp1">You can <strong>install only the required packages</strong> needed for Swagger Web API documentation from Nuget Package Manager</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/swagger/swagger-aspnetcore-nuget-package.jpg" alt="swagger aspnetcore nuget package"/></figure>



<br><br>



<h2 class="wp-block-heading" id="step-2-configure-swagger-in-startup-cs"><strong>Step 2: Configure Swagger in Startup.cs</strong></h2>



<p class="custp1">Open your project&#8217;s <span class="spanHT">Startup.cs</span> file, where you configure your application&#8217;s services and middleware. Add the following code to configure Swagger:</p>



<pre class="pchl"><code><span class="key">using</span> Microsoft.OpenApi.Models;
<span class="key">using</span> System;
<span class="key">using</span> System.IO;
<span class="key">using</span> System.Reflection;


<span class="key">public</span> <span class="key">void</span> ConfigureServices(<span class="custkey">IServiceCollection</span> services)
{
	<span class="com">// ...</span>

	services.AddSwaggerGen(swagger =&gt;
	{
		<span class="com">//This is to generate the Default UI of Swagger Documentation  </span>
		swagger.SwaggerDoc(<span class="str">"v1"</span>, <span class="key">new</span> <span class="custkey">OpenApiInfo</span>
		{
			Version = <span class="str">"v1"</span>,
			Title = <span class="str">"My App"</span>,
			Description = <span class="str">"About Application"</span>
		});

		<span class="com">// Set the comments path for the Swagger JSON and UI.</span>
		<span class="key">var</span> xmlFile = $<span class="str">"{<span class="custkey">Assembly</span>.GetExecutingAssembly().GetName().Name}.xml"</span>;
		<span class="key">var</span> xmlPath = <span class="custkey">Path</span>.Combine(<span class="custkey">AppContext</span>.BaseDirectory, xmlFile);
		swagger.IncludeXmlComments(xmlPath);                
	});
}


<span class="key">public</span> <span class="key">void</span> Configure(<span class="custkey">IApplicationBuilder</span> app, <span class="custkey">IWebHostEnvironment</span> env)
{
	<span class="com">// ...</span>

	<span class="com">// Enable middleware to serve generated Swagger as a JSON endpoint.</span>
	app.UseSwagger();

	<span class="com">// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),</span>
	<span class="com">// specifying the Swagger JSON endpoint.</span>
	app.UseSwaggerUI(c =&gt;
	{
		c.SwaggerEndpoint(<span class="str">"/swagger/v1/swagger.json"</span>, <span class="str">"Your API Name v1"</span>);
	});
} </code></pre>



<p class="custp1">In the code above, you are configuring Swagger in the <strong>ConfigureServices</strong> and <strong>Configure</strong> methods of your <strong>Startup.cs</strong> file. Make sure to replace <strong>&#8220;Your API Name&#8221;</strong> with the actual name of your API.</p>



<br><br>



<h2 class="wp-block-heading" id="step-3-define-api-documentation"><strong>Step 3: Define API Documentation</strong></h2>



<p class="custp1">Now, let&#8217;s add documentation to your API endpoints. Decorate your controllers and actions with XML comments that Swagger will use to generate documentation. For example:</p>



<pre class="pchl"><code><span class="com">/// &lt;summary&gt;</span>
<span class="com">/// This is a sample controller for managing products.</span>
<span class="com">/// &lt;/summary&gt;</span>
[<span class="custkey">ApiController</span>]
[<span class="custkey">Route</span>(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> <span class="custkey">WeatherForecastController</span> : <span class="custkey">ControllerBase</span>
{
    <span class="com">/// &lt;summary&gt;</span>
    <span class="com">/// Gets a list of all WeatherForecast.</span>
    <span class="com">/// &lt;/summary&gt;</span>
    <span class="com">/// &lt;returns&gt;A list of WeatherForecast.&lt;/returns&gt;</span>
    [<span class="custkey">HttpGet</span>]
    <span class="key">public</span> <span class="custkey">IEnumerable</span>&lt;<span class="custkey">WeatherForecast</span>&gt; Get()
    {
        <span class="com">// Your action code here</span>
    }
    <span class="com">// Add similar XML comments for other actions</span>
} </code></pre>



<p>After adding descriptions to the APIs, go to the Swagger URL and check the documentation.</p>



<br>



<h2 class="wp-block-heading" id="step-4-generate-swagger-documentation"><strong>Step 4: Generate Swagger Documentation</strong></h2>



<p class="custp1">With the configuration and documentation in place, you can now generate Swagger documentation by running your application. Build and run your .NET Core application, and navigate to URL <span class="spanHT"><strong>https://localhost:&lt;port&gt;/swagger</strong></span> or <span class="spanHT"><strong>https://localhost:&lt;port&gt;/swagger/index.html</strong></span> in your browser. You should see the Swagger UI, where you can interactively explore and test your API.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/swagger/swagger-api-documentation-sample.jpg" alt="swagger api documentation sample"/></figure>



<br><br>



<p>If you want to launch the Swagger URL by default then change the value of <span class="spanHT">launchUrl</span> in <span class="spanHT">launchSettings.json</span> file, See the screenshot below:</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/swagger/launch-swagger-default-setting.jpg" alt="launch swagger default setting"/></figure>



<br><br>



<h3 class="wp-block-heading"><strong>Troubleshooting</strong></h3>



<p class="custp1">You might get <strong>System.IO.FileNotFoundException</strong> error &#8211; &#8220;<strong>Could not find file </strong>&#8216;filePath/appfilename<strong>.xml</strong>&#8216;&#8221; as shown in the below screenshot.</p>



<h5 class="wp-block-heading"><strong><span style="text-decoration: underline;"><em> XML comments file could not be found &#8211; Swagger</em></span></strong></h5>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/swagger/xml-comments-file-could-not-be-found.jpg" alt="xml comments file could not be found"/></figure>



<p class="custp1">In such case, you can enable <strong>DocumentationFile </strong>property, manually. There are two ways to do it:</p>



<p><strong>Option 1)</strong> Go to <span class="spanHT">.csproj</span> project file and add the <span class="spanHT">GenerateDocumentationFile</span> tag within <span class="spanHT">PropertyGroup</span>:</p>



<div><b><i><u>.csproj &#8211; file</u></i></b></div>



<pre class="pchl"><code><span class="key">&lt;</span><span class="str">PropertyGroup</span><span class="key">&gt;</span>
	<span style="background:#f2f19d;"><span class="key">&lt;</span><span class="str">GenerateDocumentationFile</span><span class="key">&gt;</span>true<span class="key">&lt;/</span><span class="str">GenerateDocumentationFile</span><span class="key">&gt;</span> </span>
<span class="key">&lt;/</span><span class="str">PropertyGroup</span><span class="key">&gt;</span></code></pre>



<br>



<p class="custp1"><strong>Option 2)</strong> If you want to avoid editing the .csproj manually then right-click on <strong>app </strong>&gt;&gt; click on <strong>Properties </strong>&gt;&gt; Select <strong>Build </strong>and tick <span class="spanHT">XML documentation file</span> checkbox under the <strong>output </strong>section. See the screenshot below:</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/swagger/enable-xml-documentation-file-cjproj-property.jpg" alt="xml documentation file cjproj property"/></figure>



<br>



<p>It will add the <strong>DocumentationFile </strong>tag in PropertyGroup automatically.</p>



<div><b><i><u>.csproj &#8211; file</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/swagger/documentation-file-property-tag.jpg" alt="documentation file property tag"/></figure>



<div id="PageInAd2"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd2.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd2').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd2:', error);
	});
</script>



<br><div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>popular readings:</i></b></span>
		<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
			<div><b>&#8211; <a href="https://www.codeindotnet.com/send-calendar-invite-appointment-attachment/">[C#] calendar invite/appointment as email attachment (.net)</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/send-email-attachment-footer-meeting-invite/">[C#] Send email with attachment, footer &amp; calendar invite (.net)</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-integrate-mailchimp-v3-0-api-in-dotnet-core-c/">How to Integrate MailChimp v3.0 API in DotNet Core C#</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/export-dataset-to-excel-in-c-net-core-openxml/">Export DataSet To Excel in C# .Net Core &#8211; OpenXml</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-use-dynamic-parameters-in-dapper-2-0-in-c-net-core/">How To Use Dynamic Parameters In Dapper 2.0 In C# .Net Core?</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/sonarlint-code-clean-up-for-ms-visual-studio-cyclomatic-complexity-explained/">SonarLint Code Clean-up for MS Visual Studio &amp; Cyclomatic Complexity Explained</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/what-is-api-application-programming-interface/">What is an API – Application Programming Interface</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/send-calendar-invite-appointment-attachment/">[C#] calendar invite/appointment as email attachment (.net)</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/send-email-attachment-footer-meeting-invite/">[C#] Send email with attachment, footer &amp; calendar invite (.net)</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/install-cloudflare-free-ssl-certificate-on-godaddy/">Configure free Cloudflare SSL certificate for Godaddy Shared Webhosting</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/create-wordpress-custom-plugin-in-3-steps/">How to Create Custom WordPress Plugin: 3 Easy Steps</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-create-mime-types-class-in-c-net-core/">How to Create MIME Types Custom Class in C#</a></b></div>

		</div>
	</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[C#] calendar invite/appointment as email attachment (.net)</title>
		<link>https://www.codeindotnet.com/send-calendar-invite-appointment-attachment/</link>
					<comments>https://www.codeindotnet.com/send-calendar-invite-appointment-attachment/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 21 Aug 2023 05:09:52 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[calendar invite .ics attachment C#]]></category>
		<category><![CDATA[calendar meeting request via C# code]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=4517</guid>

					<description><![CDATA[Create Calendar Invite Content &#8211; C# code 1) Just &#8220;copy &#38; paste&#8221; the below code and modify &#8211; Start &#38; End meeting datetime, meeting link/ location, body content, subject text, sender &#38; attendee email ids. Copy code StringBuilder strInvite = new StringBuilder(); strInvite.AppendLine("BEGIN:VCALENDAR"); strInvite.AppendLine("PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN"); strInvite.AppendLine("VERSION:2.0"); strInvite.AppendLine(string.Format("METHOD:{0}", (isCancel ? "CANCEL" : "REQUEST"))); strInvite.AppendLine("METHOD:REQUEST"); [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>



<h2 class="wp-block-heading"><strong>Create Calendar Invite Content &#8211; C# code</strong></h2>



<br>



<p>1) Just &#8220;copy &amp; paste&#8221; the below code and modify &#8211; Start &amp; End meeting datetime, meeting link/ location, body content, subject text, sender &amp; attendee email ids.</p>



<button class="c-b-s-f-r" onclick="ctc('div1',this)">Copy code</button>
<br>
<div id="div1">
<pre class="pchl"><code>
<span class="key">StringBuilder</span> <span style="background:#f2f19d;">strInvite</span> = new <span class="key">StringBuilder</span>();

strInvite.AppendLine(<span class="str">"BEGIN:VCALENDAR"</span>);
strInvite.AppendLine(<span class="str">"PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN"</span>);
strInvite.AppendLine(<span class="str">"VERSION:2.0"</span>);
strInvite.AppendLine(<span class="key">string</span>.Format("METHOD:{0}", (isCancel ? "CANCEL" : "REQUEST")));
strInvite.AppendLine(<span class="str">"METHOD:REQUEST"</span>);
strInvite.AppendLine(<span class="str">"BEGIN:VEVENT"</span>);

strInvite.AppendLine(<span class="key">string</span>.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.Now.ToUniversalTime()));

<span class="com">// Meeting Start DateTime</span>
strInvite.AppendLine(<span class="key">string</span>.Format("DTSTART:{0}", <span class="custkey">DateTime</span>.Now.ToUniversalTime().ToString(<span class="str">"yyyyMMddTHHmmssZ"</span>)));

strInvite.AppendLine(<span class="key">string</span>.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.Now.ToUniversalTime()));

<span class="com">// Meeting End DateTime</span>
strInvite.AppendLine(<span class="key">string</span>.Format("DTEND:{0:}", <span class="custkey">DateTime</span>.Now.AddHours(1).ToUniversalTime().ToString(<span class="str">"yyyyMMddTHHmmssZ"</span>)));

strInvite.AppendLine(<span class="key">string</span>.Format("LAST-MODIFIED:{0:yyyyMMddTHHmmssZ}", DateTime.Now.ToUniversalTime()));

<span class="com">// web meeting link</span>
strInvite.AppendLine(<span class="key">string</span>.Format("LOCATION: {0}", eventUrlLink));
//or
//strInvite.AppendLine(<span class="key">string</span>.Format("LOCATION: {0}", eventLocationLink));

strInvite.AppendLine("PRIORITY: 5");
strInvite.AppendLine("SEQUENCE: 0");

strInvite.AppendLine(<span class="key">string</span>.Format("UID:{0}", (eventID.HasValue ? "EventId" + eventID : Guid.NewGuid().To<span class="key">string</span>())));

<span class="com">// meeting realted message body content</span>
strInvite.AppendLine(<span class="key">string</span>.Format("DESCRIPTION:{0}", strMessageBody.Replace("\n", "<br>")));
strInvite.AppendLine(<span class="key">string</span>.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", strMessageBody.Replace("\n", "<br>")));

<span class="com">// meeging subject text</span>
strInvite.AppendLine(<span class="key">string</span>.Format("SUMMARY:{0}", subjectText));
strInvite.AppendLine("STATUS:CONFIRMED"); 

<span class="com">// sender email id</span>
strInvite.AppendLine(<span class="key">string</span>.Format("ORGANIZER;CN={0}:MAILTO:{1}", strMailFrom, strMailFrom));

<span class="com">// attendee email ids for meeting</span>
strInvite.AppendLine(<span class="key">string</span>.Format("ATTENDEE;CN={0};RSVP=TRUE:mailto:{1}", <span class="key">string</span>.Join(",", strAttendeeMailTo), <span class="key">string</span>.Join(",", strAttendeeMailTo)));

strInvite.AppendLine("BEGIN:VALARM");
strInvite.AppendLine("TRIGGER:-PT15M");
strInvite.AppendLine("ACTION:DISPLAY");
strInvite.AppendLine("DESCRIPTION:Reminder");
strInvite.AppendLine("END:VALARM");
strInvite.AppendLine("END:VEVENT");
strInvite.AppendLine("END:VCALENDAR");
</code></pre>
</div>



<br><br>



<h2 class="wp-block-heading"><strong>2) Attach created Calendar invite to mail as <strong>(.ics) attachment</strong></strong></h2>



<button class="c-b-s-f-r" onclick="ctc('div2',this)">Copy code</button>
<br>
<div id="div2">
<pre class="pchl"><code>
<span class="com">// create instance of MailMessage object</span>
<span class="custkey">MailMessage</span> mailMessage = <span class="key">new</span> <span class="custkey">MailMessage</span>
{
	<span class="com">// fill normal mail body content</span>
	From = <span class="key">new</span> <span class="custkey">MailAddress</span>(strMailFrom, strSenderName),
	Subject = strSubject,
	Body = strBodyContent,
	IsBodyHtml = <span class="key">true</span>
};

<span class="com">// attach meeting request calendar invite .ics file</span>
<span class="key">byte</span>[] byteArray = <span class="custkey">Encoding</span>.ASCII.GetBytes(<span style="background:#f2f19d;">strInvite</span>);
<span class="custkey">MemoryStream</span> stream = <span class="key">new</span> <span class="custkey">MemoryStream</span>(byteArray);
<span class="custkey">Attachment</span> attach = <span class="key">new</span> <span class="custkey">Attachment</span>(stream, <span class="str">"event-meeting.<b>ics</b>"</span>);
mailMessage.Attachments.Add(attach);

<span class="com">// send mail</span>
<span class="custkey">SmtpClient</span> smtpClient = <span class="key">new</span> <span class="custkey">SmtpClient</span>
{
	<span class="com">// your credentials</span>
};

smtpClient.Send(mailMessage);

</code></pre>
</div>



<br>



<div class="note">
<div style="padding-top:0.375rem"> Looking for <b>full code</b>? Check this link &#8211; <a class="cLink" href="https://www.codeindotnet.com/send-email-attachment-footer-meeting-invite/" target="_blank" rel="noreferrer noopener nofollow"><strong>Sending email with file attachment, image as footer &amp; calendar invite attachment</strong></a></div>
</div>



<br>



<div><b><i><u>output:</u></i></b></div>



<figure class="wp-block-image size-full"><img decoding="async" width="369" height="412" src="https://www.codeindotnet.com/wp-content/uploads/2023/08/calendar-invite-appointment-ics-file.jpg" alt="calendar invite appointment .ics file C#" class="wp-image-4564" srcset="https://www.codeindotnet.com/wp-content/uploads/2023/08/calendar-invite-appointment-ics-file.jpg 369w, https://www.codeindotnet.com/wp-content/uploads/2023/08/calendar-invite-appointment-ics-file-269x300.jpg 269w" sizes="(max-width: 369px) 100vw, 369px" /></figure>



<br>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/send-calendar-invite-appointment-attachment/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[C#] Send email with attachment, footer &#038; calendar invite (.net)</title>
		<link>https://www.codeindotnet.com/send-email-attachment-footer-meeting-invite/</link>
					<comments>https://www.codeindotnet.com/send-email-attachment-footer-meeting-invite/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 20 Aug 2023 15:27:51 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[adding calendar invite via C# code]]></category>
		<category><![CDATA[embed inline image in email .net]]></category>
		<category><![CDATA[gmail file attachment with using C# code]]></category>
		<category><![CDATA[smtp.gmail.com dot net core C#]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=3539</guid>

					<description><![CDATA[Sending emails with attachments is a common task in many applications, whether it&#8217;s for sharing documents, images, or other files with recipients. In this article, we will explore how to send an email with a file attachment including inserting an image as a footer after the HTML body content, as well as creating a meeting [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8982643024325578"
     crossorigin="anonymous"></script>
<!-- PageInHoriAd1 -->
<ins class="adsbygoogle"
     style="width:728px;height:90px"
     data-ad-client="ca-pub-8982643024325578"
     data-ad-slot="5888630892"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>



<br>



<p>Sending emails with attachments is a common task in many applications, whether it&#8217;s for sharing documents, images, or other files with recipients. In this article, we will explore <strong>how to send an email with a file attachment</strong> including inserting an <strong>image as a footer</strong> after the HTML body content, as well as <strong>creating a meeting invitation through &#8216;.ICS&#8217; file attachment</strong> <strong>using C# code</strong>, making use of the built-in .NET framework classes.</p>



<p>The below screenshot shows a sample output generated through C# code which covers all the methods &amp; logic required for sending an email via the SMTP server.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="574" height="488" src="https://www.codeindotnet.com/wp-content/uploads/2023/08/successful-sending-mail-received-sample-.net-code-C.jpg" alt="send smtp email with attachment using C# code in dotnet core" class="wp-image-4368" srcset="https://www.codeindotnet.com/wp-content/uploads/2023/08/successful-sending-mail-received-sample-.net-code-C.jpg 574w, https://www.codeindotnet.com/wp-content/uploads/2023/08/successful-sending-mail-received-sample-.net-code-C-300x255.jpg 300w" sizes="auto, (max-width: 574px) 100vw, 574px" /></figure>



<br><br>



<h2 class="wp-block-heading" id="for-sending-emails-we-need"><strong>For sending emails, we need:</strong></h2>



<ul class="wp-block-list">
<li>Email settings (SMTP server, port number, sender email credentials, recipient email addresses).</li>



<li>HTML Message/ body content.</li>



<li>File for Attachment.</li>



<li>File (Image) for adding logo in the footer section (using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.linkedresource?view=net-7.0" target="_blank" rel="noopener">LinkedResource</a> &amp; <a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.alternateview?view=net-7.0" target="_blank" rel="noopener">AlternateView</a> Classes).</li>



<li>Calendar invitations (.ics) file for a meeting request or Calendar invite. (Calendar Appointment As Email Attachment)</li>
</ul>



<br>



<p>Let&#8217;s start implementing sending-email functionality in the .Net project using <a href="https://www.codeindotnet.com/c-version-history-and-features/">C#</a> code, step-by-step.</p>



<br><br>



<h2 class="wp-block-heading" id="set-up-your-project"><strong>Set Up Your Project</strong></h2>



<br>



<p>First, create a new C# application project in your preferred development environment. </p>



<p>For demo purposes, we will implement this code in the Web API project. The folder and file structure of the solution project is shown below.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/sendmail/send-mail-dotnet-core-project-solution.jpg" alt=""/></figure>



<br><br><br>



<h2 class="wp-block-heading" id="configuring-email-settings"><strong>Configuring Email Settings</strong></h2>



<br>



<p>To send an email, you need a valid SMTP (Simple Mail Transfer Protocol) server address, a valid email address for the sender, and the recipient&#8217;s email address. </p>



<p>We will use Gmail as SMTP server in our example. Ensure you have access to this basic information before proceeding.   </p>



<pre class="pchl"><code>1) smtp server = <span class="str">"smtp.gmail.com"</span>;
2) port = 587; <span class="com">// Change if your SMTP server uses a different port</span>
3) sender email e.g., <span class="str">"sender_email@gmail.com"</span>;
4) sender app password e.g., <span class="str">"sender_app_password"</span>;
5) recipient email e.g., <span class="str">"recipient@outlook.com"</span>; </code></pre>



<br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Important &#8211; Configure Google Security:</div>
<div style="padding-top:0.375rem"> Before proceeding further, please go to your google account and enable <b>2-Step Verification</b> &amp; generate an <b>app password</b> for authentication purpose as well as to establish a secure connection via code.<br>Check this link &#8211; <a class="cLink" href="https://www.codeindotnet.com/gmail-smtp-server-authentication-failed-response-code-5-7-0/#3-enable-2-step-verification-set-app-passwords-gmail-security" target="_blank" rel="noopener"><strong>How to enable 2-Step verification &amp; set app passwords in your Google account.</strong></a></div>
</div>
<br>



<div class="noteimpwar">
<div style="color:#dc2323; font-weight:bold; border-bottom:0.125rem #dc2323 solid; font-style:italic;">Note:</div>
<div style="padding-left:0.375rem; padding-top:0.375rem"> Gmail Authentication is required for sending emails. Make sure you have enabled SSL security in your Gmail Settings so that application(code) can access your mailbox.<br>If the connection is not established through a secure channel (<b>2-Step Verification</b>) then you will get an authentication failed error message &#8211; &#8220;<i>The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required</i>.&#8221;</div>
<br>
<div><center><img decoding="async" src="/img/1/sendmail/smtp-server-requires-a-secure-connection-or-the-client-was-not-authenticated.jpg" alt="SMTP server requires a secure connection or the client was not authenticated"/></center></div>
</div>



<br><br><br>



<h2 class="wp-block-heading" id="sending-email-with-content-attachments-calendar-invite-c-code"><strong>Sending Email With Content, Attachments &amp; calendar invite &#8211; C# code </strong></h2>



<br>



<p>Next, we&#8217;ll create separate classes and methods that send an email with attachments. In this example, we&#8217;ll send a simple text email with a single attachment, footer logo image &amp; meeting request(.ics file) but you can customize it to suit your needs.</p>



<br>



<h2 class="wp-block-heading" id="step-1-create-get-set-email-property-class"><strong>Step 1: Create {get set} email property class</strong></h2>



<br>



<p>Create a property class (<strong>MailTemplateProperty.cs</strong>) that will serve and get all the essential details for sending an email, such as the SMTP server address, valid email addresses for both the sender and recipient, as well as any attachments such as files, footers, and calendar invite/appointment information.</p>



<button class="c-b-s-f-r" onclick="ctc('div3',this)">Copy code</button>
<br>
<div id="div3">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MailTemplateProperty
{
	<span class="com">// <b>"SMTP Configuration/Credential"</b></span>
	<span class="key">public</span> <span class="key">string</span> SmtpClientHost { get; set; }
	<span class="key">public</span> <span class="key">int</span> SmtpClientPort { get; set; }
	<span class="key">public</span> <span class="key">bool</span> SmtpClientEnableSSL { get; set; }
	<span class="key">public</span> <span class="key">string</span> CredentialUserName { get; set; }
	<span class="key">public</span> <span class="key">string</span> CredentialPass { get; set; }

	<span class="com">// <b>"Compose Email"</b></span>
	<span class="key">public</span> <span class="key">string</span> SenderName { get; set; }
	<span class="key">public</span> <span class="key">string</span> MailFrom { get; set; }
	<span class="key">public</span> <span class="key">string</span> MailTo { get; set; }
	<span class="key">public</span> <span class="key">string</span> MailCC { get; set; }
	<span class="key">public</span> <span class="key">string</span> Subject { get; set; }
	<span class="key">public</span> <span class="key">string</span> Body { get; set; }


	<span class="com">/* <b>===== Optional Setting ===== */</b></span>

	<span class="com">// <b>"File attachments"</b></span>
	<span class="key">public</span> <span class="custkey">Attachment</span> Attachment { get; set; } = null;

	<span class="com">// <b>"Adding logo/image on footer"</b></span>
	<span class="key">public</span> <span class="key">string</span> Footer { get; set; } = null;

	<span class="com">// <b>Attach Calendar or meeting properties</b></span>
	<span class="key">public</span> <span class="key">string</span> StartDateTime { get; set; }
	<span class="key">public</span> <span class="key">string</span> EndDateTime { get; set; }
	<span class="key">public</span> <span class="key">string</span> EventLink { get; set; }
	<span class="key">public</span> <span class="key">string</span> EventLocation { get; set; }
	<span class="key">public</span> <span class="key">string</span> Attendee { get; set; }
} 
</code></pre>
</div>



<br><br>



<h2 class="wp-block-heading" id="step-2-create-a-class-methods-to-send-mail"><strong>Step 2: Create a Class &amp; methods to send mail</strong></h2>



<br>



<p>It is a good practice to keep all email-sending related functionalities in a separate Class. We create a class called &#8216;<strong>Mail.cs</strong>&#8216; with a function called &#8216;<strong>Send()</strong>&#8216; inside. This function sends an email using the details you provide.</p>



<p>We need to implement all mail-related logic and code implementation in this class, such as:</p>



<h3 class="wp-block-heading" id="a-file-attachment"><strong>a) File attachment</strong></h3>



<p>Use the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.attachment?view=net-7.0" target="_blank" rel="noopener">Attachment</a> Class from &#8216;System.Net.Mail&#8217; Namespace. In this example, the code shows that you can pass a file as a parameter either by passing &#8216;file as MemoryStream with the name&#8217; or mentioning the full physical path &amp; name of the file. </p>



<h3 class="wp-block-heading" id="b-attaching-logo-image-as-footer-note-inline"><strong>b) Attaching Logo Image as footer note(inline)</strong></h3>



<p>We need to use LinkedResource &amp; AlternateView Classes in the mail code to display embedded image(s) in the footer section. How to work with Alternate view &#8211; To add an alternate view to a MailMessage object, create an Attachment for the view, and then add it to the collection returned by AlternateViews. Use the Body property to specify the text version and use the AlternateViews collection to specify views with other MIME types.</p>



<h3 class="wp-block-heading" id="c-calendar-appointment-as-email-attachment-ics"><strong>c) Calendar Appointment As Email Attachment (.ics)</strong></h3>



<p>Calendar invitation or &#8216;. ics&#8217; file is a calendar file saved in a universal calendar format used by several email and calendar programs, including Google Calendar, Microsoft Outlook, and Apple Calendar. It allows adding a calendar link in an email message and users to share the event information on the web and over email which will alert/ remind recipients prior to scheduled meeting time.</p>



<h3 class="wp-block-heading" id="d-common-logic"><strong>d) <span style="text-decoration: underline;">Common logic</span></strong></h3>



<ul class="wp-block-list">
<li>accepting mail body (plain text or HTML as string) and subject text</li>



<li>Getting mandatory credential info so that mail can be sent without any failure </li>
</ul>



<p>All of these functionalities &amp; logic have been incorporated in the code provided below. </p>



<br><br>



<p><span><span style="font-weight: bold; font-style: italic; text-decoration: underline;">Mail.cs &#8211; full code</span></span> &#8211; just copy &amp; paste</p>



<p>Ensure you have added the necessary namespace for email functionality.</p>



<button class="c-b-s-f-r" onclick="ctc('div1',this)">Copy code</button>
<br>
<div id="div1">
<pre class="pchl"><code><span class="key">using</span> System.Net;
<span class="key">using</span> System.Net.Mail;
<span class="key">using</span> System.Net.Mime;
<span class="key">using</span> System.Text; </code></pre>
</div>



<br>



<div>Code implementation.</div>



<button class="c-b-s-f-r" onclick="ctc('div4',this)">Copy code</button>
<br>
<div id="div4"><pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Mail
{
	<h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Main method for sending mail</b></span></h3>	<span class="key">public</span> <span class="key">static</span> <span class="key">bool</span> Send(MailTemplateProperty mailTemplate)
	{
		<span class="key">string</span> meetingMessageBody = mailTemplate.Body;

		mailTemplate.MailFrom = mailTemplate.MailFrom.Trim(',').Trim(';');

		<span class="key">if</span> (string.IsNullOrEmpty(mailTemplate.MailFrom))
			<span class="key">return</span> false;
		<span class="key">try</span>
		{
			<span class="custkey">MailMessage</span> mailMessage = <span class="key">new</span> <span class="custkey">MailMessage</span>
			{
				From = <span class="key">new</span> <span class="custkey">MailAddress</span>(mailTemplate.MailFrom,
								string.IsNullOrEmpty(mailTemplate.SenderName) ? mailTemplate.MailFrom : mailTemplate.SenderName),
				Subject = mailTemplate.Subject,
				Body = mailTemplate.Body,
				IsBodyHtml = <span class="key">true</span>
			};

			<h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Adding File Attachment</b></span></h3>
			<span class="key">if</span> (<span class="key">null</span> != mailTemplate.Attachment)
				mailMessage.Attachments.Add(mailTemplate.Attachment);

<h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Adding To &amp; CC email addresses, </b></span></h3>
			mailTemplate.MailTo = mailTemplate.MailTo.Trim();
			mailMessage.To.Add(mailTemplate.MailTo);
			<span class="key">if</span> (!string.IsNullOrEmpty(mailTemplate.MailCC) &amp;&amp; mailTemplate.MailCC.Length &gt; 0)
				mailMessage.CC.Add(mailTemplate.MailCC);

<h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Adding logo-Image as Footer</b></span></h3>
			<span class="key">if</span> (mailTemplate.Footer != <span class="key">null</span>)
			{
				<span class="custkey">LinkedResource</span> res = <span class="key">new</span> <span class="custkey">LinkedResource</span>(mailTemplate.Footer)
				{
					ContentId = Guid.NewGuid().ToString()
				};
				mailTemplate.Body += @<span class="str">"&lt;img src='cid:"</span> + res.ContentId + @<span class="str">"'/&gt;"</span>;
				<span class="custkey">AlternateView</span> avHtml = <span class="custkey">AlternateView</span>.CreateAlternateViewFromString(mailTemplate.Body, <span class="key">null</span>, <span class="custkey">MediaTypeNames</span>.<span class="custkey">Text</span>.Html);
				avHtml.LinkedResources.Add(res);
				mailMessage.AlternateViews.Add(avHtml);
			}

<h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Adding Meeting Request</b></span></h3>
			<span class="key">byte</span>[] byteArray = <span class="custkey">Encoding</span>.ASCII.GetBytes(MeetingRequestString(mailTemplate.Subject, meetingMessageBody, mailTemplate));
			<span class="custkey">MemoryStream</span> stream = <span class="key">new</span> <span class="custkey">MemoryStream</span>(byteArray);
			<span class="custkey">Attachment</span> attach = <span class="key">new</span> <span class="custkey">Attachment</span>(stream, <span class="str">"event-meeting.ics"</span>);
			mailMessage.Attachments.Add(attach);

<h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Finally, sending mail via Gmail, SMTP client info with credentials.</b></span></h3>
			<span class="custkey">SmtpClient</span> smtpClient = <span class="key">new</span> <span class="custkey">SmtpClient</span>
			{
				Host = mailTemplate.SmtpClientHost,
				Port = mailTemplate.SmtpClientPort,
				EnableSsl = mailTemplate.SmtpClientEnableSSL,
				Credentials = <span class="key">new</span> <span class="custkey">NetworkCredential</span>(mailTemplate.CredentialUserName, mailTemplate.CredentialPass),
			};

<h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Send mail by SMTP.</b></span></h3>
			smtpClient.Send(mailMessage);

			<span class="key">return</span> true;
		}
		<span class="key">catch</span> (SmtpFailedRecipientException ex)
		{
			<span class="com">// LogError(ex.ToString());</span>
			<span class="key">return</span> false;
			<span class="com">//throw new Exception();</span>
		}
		<span class="key">catch</span> (SmtpException ex)
		{
			<span class="com">// LogError(ex.ToString());</span>
			<span class="key">return</span> false;
			<span class="com">//throw new Exception();</span>
		}
		<span class="key">catch</span> (Exception ex)
		{
			<span class="com">// LogError(ex.ToString());</span>
			<span class="key">return</span> false;
			<span class="com">//throw new Exception();</span>
		}
	}


<h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Email Meeting Request- ics meeting/ Calendar invite Code</b></span></h3><h3 style="padding-left:25px;"><span style="color:#19ad19;"><b>// Attaching calendar appointment</b></span></h3>
	<span class="key">private</span> <span class="key">static</span> <span class="key">string</span> MeetingRequestString(<span class="key">string</span> subject, <span class="key">string</span> messageBody, MailTemplateProperty mailTemplate, int? eventID = <span class="key">null</span>, <span class="key">bool</span> isCancel = <span class="key">false</span>)
	{
		StringBuilder str = <span class="key">new</span> StringBuilder();

		str.AppendLine(<span class="str">"BEGIN:VCALENDAR"</span>);
		str.AppendLine(<span class="str">"PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN"</span>);
		str.AppendLine(<span class="str">"VERSION:2.0"</span>);
		str.AppendLine(string.Format(<span class="str">"METHOD:{0}"</span>, (isCancel ? <span class="str">"CANCEL"</span> : <span class="str">"REQUEST"</span>)));
		str.AppendLine(<span class="str">"METHOD:REQUEST"</span>);
		str.AppendLine(<span class="str">"BEGIN:VEVENT"</span>);

		str.AppendLine(string.Format(<span class="str">"CREATED:{0:yyyyMMddTHHmmssZ}"</span>, DateTime.Now.ToUniversalTime()));

		<span class="com">// Date format - yyyyMMddTHHmmssZ</span>
		str.AppendLine(string.Format(<span class="str">"DTSTART:{0}"</span>, mailTemplate.StartDateTime));
		str.AppendLine(string.Format(<span class="str">"DTSTAMP:{0:yyyyMMddTHHmmss}"</span>, DateTime.Now.ToUniversalTime()));
		str.AppendLine(string.Format(<span class="str">"DTEND:{0:}"</span>, mailTemplate.EndDateTime));

		str.AppendLine(string.Format(<span class="str">"LAST-MODIFIED:{0:yyyyMMddTHHmmssZ}"</span>, DateTime.Now.ToUniversalTime()));

		<span class="com">// web meeting link</span>
		str.AppendLine(string.Format(<span class="str">"LOCATION: {0}"</span>, mailTemplate.EventLink));
		<span class="com">//or</span>
		<span class="com">//str.AppendLine(string.Format("LOCATION: {0}", mailTemplate.EventLocation));</span>

		str.AppendLine(<span class="str">"PRIORITY: 5"</span>);
		str.AppendLine(<span class="str">"SEQUENCE: 0"</span>);

		str.AppendLine(string.Format(<span class="str">"UID:{0}"</span>, (eventID.HasValue ? <span class="str">"EventId"</span> + eventID : Guid.NewGuid().ToString())));
		str.AppendLine(string.Format(<span class="str">"DESCRIPTION:{0}"</span>, messageBody.Replace(<span class="str">"\n"</span>, <span class="str">"&lt;br&gt;"</span>)));
		str.AppendLine(string.Format(<span class="str">"X-ALT-DESC;FMTTYPE=text/html:{0}"</span>, messageBody.Replace(<span class="str">"\n"</span>, <span class="str">"&lt;br&gt;"</span>)));
		str.AppendLine(string.Format(<span class="str">"SUMMARY:{0}"</span>, subject));
		str.AppendLine(<span class="str">"STATUS:CONFIRMED"</span>); 
		str.AppendLine(string.Format(<span class="str">"ORGANIZER;CN={0}:MAILTO:{1}"</span>, mailTemplate.MailFrom, mailTemplate.MailFrom));
		str.AppendLine(string.Format(<span class="str">"ATTENDEE;CN={0};RSVP=TRUE:mailto:{1}"</span>, string.Join(<span class="str">","</span>, mailTemplate.Attendee), string.Join(<span class="str">","</span>, mailTemplate.Attendee)));

		str.AppendLine(<span class="str">"BEGIN:VALARM"</span>);
		str.AppendLine(<span class="str">"TRIGGER:-PT15M"</span>);
		str.AppendLine(<span class="str">"ACTION:DISPLAY"</span>);
		str.AppendLine(<span class="str">"DESCRIPTION:Reminder"</span>);
		str.AppendLine(<span class="str">"END:VALARM"</span>);
		str.AppendLine(<span class="str">"END:VEVENT"</span>);
		str.AppendLine(<span class="str">"END:VCALENDAR"</span>);

		<span class="key">return</span> str.ToString();
	}
} 
</code></pre>
</div>



<br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div style="padding-top:0.375rem; padding-left:1.25rem"> In this example, code will return a true (bool) value if mail is sent successfully else a false value in case of any exception(failure). You can log errors or implement other logic in the catch{} section or modify method behaviour as per your need.</div>
</div>



<br><br>



<h2 class="wp-block-heading" id="step-3-call-execute-mail-send-method"><strong>Step 3: Call &amp; execute Mail.Send() Method</strong></h2>



<br>



<p>Common C# code for sending email via SMTP is completed. Now we can call &amp; execute this Mail.Send() method from <strong>Controller (SendEmails.cs)</strong> or another code page in two steps: </p>



<h3 class="wp-block-heading" id="a-set-all-property-values"><strong>a) Set all Property values</strong></h3>



<p>Before calling the Mail.Send() method, set all necessary property values (get all input &amp; assign its values), see the sample below.</p>



<button class="c-b-s-f-r" onclick="ctc('div5',this)">Copy code</button>
<br>
<div id="div5"><pre class="pchl"><code><span class="custkey">MailTemplateProperty</span> mailTemplate = <span class="key">new</span> <span class="custkey">MailTemplateProperty</span>
{
	<span class="com">// <b>"Gmail SMTP Configuration/Credential"</b></span>
	SmtpClientHost = <span class="str">"smtp.gmail.com"</span>,
	SmtpClientPort = 587,
	SmtpClientEnableSSL = <span class="key">true</span>,
	CredentialUserName = <span class="str">"sender_emailId@example.com"</span>,
	CredentialPass = <span class="str">"google_app_password"</span>,

	<span class="com">// <b>"Compose Email"</b></span>
	SenderName = <span class="str">"Admin"</span>,
	MailFrom = <span class="str">"sender_emailId@gmail.com"</span>,
	MailTo = <span class="str">"recipient_emailId@outlook.com"</span>,
	MailCC = string.Empty,
	Subject = <span class="str">"Next Team Meeting"</span>,
	Body = <span class="str">"This is a test mail from admin.",</span>

	<span class="com">// <b>"File attachments"</b></span>
	<span class="com">//Attachment = new System.Net.Mail.Attachment(mailAttachmentFile.OpenReadStream(), "Meeging.pdf"),</span>
	<span class="com">// or</span>
	Attachment = <span class="key">new</span> System.Net.Mail.<span class="custkey">Attachment</span>(<span class="custkey">Path</span>.GetDirectoryName(<span class="custkey">Assembly</span>.GetEntryAssembly().Location) + <span class="str">"/Files/Meeting.pdf"</span>),

	<span class="com">// <b>"Adding logo/image on footer"</b></span>
	Footer = <span class="custkey">Path</span>.GetDirectoryName(<span class="custkey">Assembly</span>.GetEntryAssembly().Location) + <span class="str">"/Images/MailFooterLogo.png"</span>,

	<span class="com">// <b>Attach Calendar or meeting properties</b></span>
	StartDateTime = <span class="custkey">DateTime</span>.Now.ToUniversalTime().ToString(<span class="str">"yyyyMMddTHHmmssZ"</span>),
	EndDateTime = <span class="custkey">DateTime</span>.Now.AddHours(1).ToUniversalTime().ToString(<span class="str">"yyyyMMddTHHmmssZ"</span>),
	<span class="com">// MS Teams or Skype or webex meeting link</span>
	EventLink = <span class="str">"https://www.webex.com/test-meeting.html"</span>,
	EventLocation = <span class="str">"Online"</span>,
	Attendee = <span class="str">"recipient_emailId@outlook.com"</span>
};

</code></pre>
</div>



<br>



<h3 class="wp-block-heading" id="b-finally-call-mail-send-method"><strong>b) Finally, Call Mail.Send() Method</strong></h3>



<p>Now, call Mail.Send() method by passing &#8216;<strong>mailTemplate</strong>&#8216; object as a parameter.</p>



<button class="c-b-s-f-r" onclick="ctc('div6',this)">Copy code</button>
<br>
<div id="div6"><pre class="pchl"><code>
<span class="key">Mail</span>.Send(<b>mailTemplate</b>); 

</code></pre>
</div>



<br>



<p>That&#8217;s it, test the code. if sending mail is successful then the recipient(s) will receive the email in a few seconds. In case of failure, it will return false status as a bool value.<br>But you can also log an error or throw an exception based on your requirement.</p>



<br>



<div style="font-size:20px;"><b>Screenshots</b></div><br>



<p><strong><em><span style="text-decoration: underline;">Method 1:</span></em></strong></p>



<p>You can get the file attachment from Azure blob storage but in this example, the <strong>Meeting.pdf</strong> file is attached from the Root folder, see the below screenshot.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/sendmail/send-mail-attachment-controller-class.jpg" alt="send mail attachment from solution root folder"/></figure>



<br><br>



<p><strong><em><span style="text-decoration: underline;">Method 2:</span></em></strong></p>



<p>You can use <span class="spanHT">IFormFile</span> to receive a file as input from the front-end application and send it as an attachment, please see the implementation in the screenshot.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/sendmail/upload-and-send-mail-attachment-controller-class.jpg" alt=""/></figure>



<br><br>



<p class="brgrey" id="download-source-code"><a href="/img/1/sendmail/SendEmailWithAttachmentFooterCalendarInvite.zip"><span class="cLink3"><strong>Download Source Code</strong></span></a> and try it yourself (open sample project using Visual Studio 2022)</p>



<div>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8982643024325578"
     crossorigin="anonymous"></script>
<!-- PageInAd1 -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-8982643024325578"
     data-ad-slot="3814999883"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>



<br><br>



<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>popular readings:</i></b></span>
		<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
			<div><b>&#8211; <a href="https://www.codeindotnet.com/install-cloudflare-free-ssl-certificate-on-godaddy/">Configure free Cloudflare SSL certificate for Godaddy Shared Webhosting</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/create-wordpress-custom-plugin-in-3-steps/">How to Create Custom WordPress Plugin: 3 Easy Steps</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-create-mime-types-class-in-c-net-core/">How to Create MIME Types Custom Class in C#</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/extract-images-from-pdf-using-itext7-c-net/">How to extract images from PDF using iText7 in [C#] .Net</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/wordpress-rest-api-c-wordpresspcl-example/">Easy Integration of WordPress API in C# .Net</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/find-sitemap-website-url-link-is-exists-valid-c-dot-net-core/">Check SiteMaps XML URL Nodes for broken links C#</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/csharp-keywords-reserved-contextual/">C# Keywords (Reserved and Contextual)</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/what-is-dapper-micro-orm-in-c/">What is Dapper micro-ORM in C#?</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/c-version-history-and-features/">C# Version History and features</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-integrate-mailchimp-v3-0-api-in-dotnet-core-c/">How to Integrate MailChimp v3.0 API in DotNet Core C#</a></b></div>

		</div>
	</div>
</div>



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#for-sending-emails-we-need">For sending emails, we need:</a></li><li><a href="#set-up-your-project">Set Up Your Project</a></li><li><a href="#configuring-email-settings">Configuring Email Settings</a></li><li><a href="#sending-email-with-content-attachments-calendar-invite-c-code">Sending Email With Content, Attachments &amp; calendar invite &#8211; C# code </a></li><li><a href="#step-1-create-get-set-email-property-class">Step 1: Create {get set} email property class</a></li><li><a href="#step-2-create-a-class-methods-to-send-mail">Step 2: Create a Class &amp; methods to send mail</a><ul><li><a href="#a-file-attachment">a) File attachment</a></li><li><a href="#b-attaching-logo-image-as-footer-note-inline">b) Attaching Logo Image as footer note(inline)</a></li><li><a href="#c-calendar-appointment-as-email-attachment-ics">c) Calendar Appointment As Email Attachment (.ics)</a></li><li><a href="#d-common-logic">d) Common logic</a></li></ul></li><li><a href="#step-3-call-execute-mail-send-method">Step 3: Call &amp; execute Mail.Send() Method</a><ul><li><a href="#a-set-all-property-values">a) Set all Property values</a></li><li><a href="#b-finally-call-mail-send-method">b) Finally, Call Mail.Send() Method</a></li></ul></li></ul></nav></div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/send-email-attachment-footer-meeting-invite/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>How to Integrate MailChimp v3.0 API in DotNet Core C#</title>
		<link>https://www.codeindotnet.com/how-to-integrate-mailchimp-v3-0-api-in-dotnet-core-c/</link>
					<comments>https://www.codeindotnet.com/how-to-integrate-mailchimp-v3-0-api-in-dotnet-core-c/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 12 Apr 2022 08:12:15 +0000</pubDate>
				<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[mailchimp]]></category>
		<category><![CDATA[mailchimp api]]></category>
		<category><![CDATA[mailchimp api wrapper]]></category>
		<category><![CDATA[mailchimp audience]]></category>
		<category><![CDATA[mailchimp campaign]]></category>
		<category><![CDATA[mailchimp campaign report]]></category>
		<category><![CDATA[mailchimp csharp]]></category>
		<category><![CDATA[mailchimp email template]]></category>
		<category><![CDATA[mailchimp nuget package]]></category>
		<category><![CDATA[mailchimp subscriber]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=505</guid>

					<description><![CDATA[In this post, we will discuss how to use MailChimp in the .Net Core application, which Nuget Package needs to be used, how to create or add Audience, Subscribers, Email Template, Campaign, and generate reports using C# code. We will be using the MailChimp.Net.V3 Nuget package developed by Brandon Seydel. It is a .Net Wrapper [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>



<div id="PageInHoriAd1"></div>
<script>
fetch('/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<p>In this post, we will discuss how to use <strong><mark style="background-color:#e3e7ea" class="has-inline-color">MailChimp</mark><mark style="background-color:#ffffff" class="has-inline-color"> </mark></strong>in the <strong><mark style="background-color:#e3e7ea" class="has-inline-color">.Net Core</mark></strong> application, which <strong><mark style="background-color:#e3e7ea" class="has-inline-color">Nuget Package</mark></strong> needs to be used, how to create or add Audience, Subscribers, Email Template, Campaign, and generate reports using <strong><mark style="background-color:#e3e7ea" class="has-inline-color">C# code</mark></strong>. We will be using the <strong>MailChimp.Net.V3</strong> Nuget package <strong>developed by Brandon Seydel</strong>. It is a .Net Wrapper for Mail Chimp <strong><a href="https://www.codeindotnet.com/what-is-api-application-programming-interface/" data-type="post" data-id="18" target="_blank" rel="noreferrer noopener">API</a></strong> and easy to implement with a few lines of code.</p>



<figure class="wp-block-image size-full is-style-default"><img loading="lazy" decoding="async" width="426" height="79" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-api-brandon-seydel.png" alt="MailChimp.net.v3 by Brandon Seydel" class="wp-image-565" title="" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-api-brandon-seydel.png 426w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-api-brandon-seydel-300x56.png 300w" sizes="auto, (max-width: 426px) 100vw, 426px" /></figure>



<br>



<p>First, let&#8217;s understand MailChimp and how to use it.</p>



<h2 class="wp-block-heading"><strong>What is MailChimp?</strong> </h2>



<p>Mailchimp is an Email Service Provider (ESP) and one of the most famous <strong>email marketing</strong> software or platforms in today’s world. It is used to develop &amp; <strong>manage newsletters</strong>, and send automated emails to the customers (list of users). Assume you have a mailing list and want to send a weekly <strong>newsletter </strong>to every individual. This process can be automated with MailChimp service and you can reach out to your client, customer, and other interested parties to grow your business.</p>



<h2 class="wp-block-heading"><strong>Free to use</strong></h2>



<p>It is free to use up to 2000 contacts with a limit of 10,000 emails per month with a daily limit of 2,000 </p>



<p><strong>A free plan is also available</strong> which allows you to add 2000 contacts and send 10,000 emails per month with a daily limit of 2,000.</p>



<h2 class="wp-block-heading"><strong>How to send marketing emails via MailChimp?</strong></h2>



<p>Below are the basic steps to send emails to target users (subscribers). </p>



<p>1) <strong><a href="#Create-an-Audience">Create an Audience</a></strong> – it is just like a group name, for example, the <strong>Audience Name</strong> could be named as WeeklyNewsGrp. In code, we will be using <strong>Audience ID</strong>.<br>2) <strong><a href="#Add-subscribers">Add subscribers</a></strong> – adding email addresses to an Audience.<br>3) <strong><a href="#Create-Template">Create Template</a></strong> – HTML content with text, images, URL, and other stuff<br>4) <strong><a href="#Create-Campaign">Create Campaign</a></strong> – final step where you must select:<br>&nbsp;&nbsp;&nbsp;&nbsp;a. <strong>To</strong> address &#8211; targeted audience name<br>&nbsp;&nbsp;&nbsp;&nbsp;b. <strong>From</strong> address<br>&nbsp;&nbsp;&nbsp;&nbsp;c. <strong>Subject</strong> &#8211; short text<br> &nbsp;&nbsp;&nbsp;&nbsp;d. <strong>Content </strong>– this is your template</p>



<p>Once all the above steps are done, either you can <strong>send it immediately or schedule</strong> it for a future date. Later, you can also generate the <a href="##Campaign-Report"><strong>Campaign Report</strong></a> to know each subscriber&#8217;s status &amp; activities.</p>



<h2 class="wp-block-heading"><strong>Using MailChimp in .Net code </strong>&#8211; <strong>C#</strong></h2>



<p>To use MailChimp in .Net Core project you need to install the <strong>MailChimp.Net.V3</strong> package,<strong> </strong>developed by Brandon Seydel. It is licensed under the&nbsp;<a href="https://github.com/brandonseydel/MailChimp.Net/blob/master/LICENSE.txt" target="_blank" rel="noopener">MIT</a>&nbsp;license. You can see more about it <a href="https://github.com/brandonseydel/MailChimp.Net" target="_blank" rel="noreferrer noopener"><strong>here</strong></a></p>



<p>Install this package in your project, for example &#8211; Business Layer.</p>



<figure class="wp-block-image size-large is-style-default"><img loading="lazy" decoding="async" width="1024" height="435" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-NuGet-github-1024x435.png" alt="install MailChimp NuGet package" class="wp-image-560" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-NuGet-github-1024x435.png 1024w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-NuGet-github-300x127.png 300w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-NuGet-github-768x326.png 768w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-NuGet-github.png 1270w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="has-white-color has-black-background-color has-text-color has-background"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-white-color">Installing from package manager console &#8211; </mark><strong><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-white-color">Install-Package</mark> <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-white-color">MailChimp.Net.V3</mark></strong></p>



<br><br>



<h2 class="wp-block-heading"><strong>Get the API Key for development</strong></h2>



<br>



<p><mark style="background-color:rgba(0, 0, 0, 0);color:#d74949" class="has-inline-color"><strong>Before you start implementing the code</strong></mark> you should have a MailChimp <strong>API Key</strong> handy. You need to pass this API Key whenever you are performing any action via code like creating an audience, adding members, getting reports, or any other request.</p>



<p><strong>1)</strong> Login into your account (you can register with a free plan for development purposes) </p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:50%">
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:100%">
<p><strong>2)</strong> Click on <strong>Account</strong> (left-hand side below) &gt;&gt; click on <strong>Account &amp; billing</strong>. It will open the account page.</p>
</div>
</div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:50%">
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="289" height="432" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/Mail-Chimp-Account-billing.png" alt="Click on MailChimp account and billing" class="wp-image-553" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/Mail-Chimp-Account-billing.png 289w, https://www.codeindotnet.com/wp-content/uploads/2022/04/Mail-Chimp-Account-billing-201x300.png 201w" sizes="auto, (max-width: 289px) 100vw, 289px" /></figure>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:50%">
<p><strong>3)</strong> Click on <strong>Extras</strong> &gt;&gt; <strong>API Keys</strong>. It will open the API Key page.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:50%">
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="150" height="184" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-api-keys.png" alt="find Mailchimp API keys" class="wp-image-556"/></figure>
</div>
</div>



<p><strong>4)</strong> you can see API Key as shown in the below screenshot.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="624" height="184" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/find-mailchimp-api-key.png" alt="copy the MailChimp API key" class="wp-image-554" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/find-mailchimp-api-key.png 624w, https://www.codeindotnet.com/wp-content/uploads/2022/04/find-mailchimp-api-key-300x88.png 300w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure>



<br>



<h2 class="wp-block-heading"><strong>Let’s start coding in C# &#8211; Mail Chimp &#8211; Step-by-Step</strong></h2>



<br>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:50%">
<p>Create a .Net application and install the MailChimp.Net.V3 NuGet package in your project.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:50%">
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="251" height="165" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-packages-solution.png" alt="Install the MailChimp NuGet package in your .Net project" class="wp-image-567"/></figure>
</div>
</div>



<p>Configure API Key in <strong>appsettings.json</strong></p>



<button class="c-b-s-f-r" onclick="ctc('div1',this)">Copy code</button>
<br>
<div id="div1"><pre class="pchl"><code><span class="custkey">"MailChimp"</span>: {
    <span class="custkey">"ApiKey"</span>: <span class="str">"60exxxx-Your-API-KEY-xxxxxxxxb8-us20"</span>
  }</code></pre></div>



<br>



<h3 class="wp-block-heading" id="Create-an-Audience"><strong>1. Create an Audience</strong></h3>



<p>First, the audience name needs to be created to add the email addresses.</p>



<p>Consider &#8220;Audience&#8221; as a group name where you need to add a list of subscribers&#8217; email Ids.</p>



<p><strong><mark style="background-color:rgba(0, 0, 0, 0);color:#d74949" class="has-inline-color">Note:</mark></strong> AudienceID is known as <strong>listId </strong>in code.</p>



<p>I have written all MailChimp related code in a separate <strong>static class </strong>so that any method can be called by just passing the necessary parameters. Create a .cs file and name it as <strong>MailChimpHelper.cs</strong>. Below is the code<strong> to add an Audience</strong>.</p>



<button class="c-b-s-f-r" onclick="ctc('div2',this)">Copy code</button>
<br>
<div id="div2"><pre class="pchl"><code><span style="background:#f2f19d;"><span class="key">using</span> MailChimp.Net;
<span class="key">using</span> MailChimp.Net.Interfaces;
<span class="key">using</span> MailChimp.Net.Models;</span>
<span class="key">using</span> System;
<span class="key">using</span> System.Collections.Generic;
<span class="key">using</span> System.Linq;
<span class="key">using</span> System.Threading.Tasks;
<span class="key">using</span> System.Web;


<span class="key">public</span> <span class="key">static</span> <span class="key">class</span> MailChimpHelper
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">async</span> Task&lt;<span class="key">string</span>&gt; AudienceAddAsync(<span class="key">string</span> apiKey, <span class="key">string</span> audienceName, Dictionary&lt;<span class="key">string</span>, <span class="key">string</span>&gt; config)
    {
        <span class="key">string</span> newAudienceId = <span class="key">string</span>.Empty;

        <span style="background:#f2f19d;">IMailChimpManager mc = <span class="key">new</span> MailChimpManager(apiKey);</span>

        <span class="key">try</span>
        {
            <span class="com">/*All inputs are mandatory.
			 Store these default values in some config file or database*/</span>
            <span class="key">var</span> audience = <span class="key">await</span> <span style="background:#f2f19d;">mc.Lists.AddOrUpdateAsync</span>(<span class="key">new</span> List
            {
                Name = audienceName,
                PermissionReminder = config[<span class="str">"PermissionReminder"</span>], <span class="com">//You are receiving this email because you opted in via our website.</span>
                Contact = <span class="key">new</span> Contact
                {
                    Company = config[<span class="str">"Company"</span>],
                    Address1 = config[<span class="str">"Address1"</span>],
                    City = config[<span class="str">"City"</span>],
                    Country = config[<span class="str">"Country"</span>],
                    State = config[<span class="str">"State"</span>],
                    Zip = config[<span class="str">"Zip"</span>]
                },

                CampaignDefaults = <span class="key">new</span> CampaignDefaults
                {
                    FromEmail = config[<span class="str">"DefaultFromEmail"</span>], <span class="com">//Registered emaild id</span>
                    FromName = config[<span class="str">"DefaultFromName"</span>],
                    Language = config[<span class="str">"DefaultLanguage"</span>], <span class="com">//"en"</span>
                    Subject = <span class="str">""</span>
                }

            });

            newAudienceId = audience.Id;

        }
        <span class="key">catch</span> (Exception ex)
        {
        }

        <span class="key">return</span> newAudienceId;

    }
}
</code></pre></div>



<br>



<p><strong>Call this static method from business class</strong> or wherever you prefer. See the sample code below.</p>



<button class="c-b-s-f-r" onclick="ctc('div3',this)">Copy code</button>
<br>
<div id="div3"><pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Business
{
    <span class="key">private</span> <span class="key">readonly</span> IConfiguration configuration;

    <span class="key">public</span> Business(IConfiguration _configuration)
    {
        configuration = _configuration;
    }

    <span class="key">public</span> <span class="key">async</span> Task CreateAudience()
    {
        <span class="com">//get the MailChimp API Key from appsettings.json</span>
        <span class="key">string</span> apiKey = configuration.GetSection(<span class="str">"MailChimp:ApiKey"</span>).Value;

        <span class="com">//Get Audience Configuration details from database or config file.</span>
        Dictionary&lt;<span class="key">string</span>, <span class="key">string</span>&gt; audienceConfig = GetAudienceConfig();

        <span class="key">string</span> newAudienceName = <span class="str">"WeeklyNewsGrp"</span>;
        <span class="key">string</span> newAudienceId = <span class="key">await</span> <span style="background:#f2f19d;">MailChimpHelper.AudienceAddAsync(apiKey, newAudienceName, audienceConfig)</span>;

        <span class="com">//save newly created Audience Id in DB</span>
        SaveNewAudienceId(newAudienceId); 
    }
}</code></pre></div>



<br>



<p><strong>Debug &#8211;</strong> Code will return the newly created &#8220;audience.Id&#8221; which is also known as &#8220;listId&#8221;.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="525" height="56" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/create-new-mailchimp-audience-id.png" alt="newly created MailChimp audience id in debug mode" class="wp-image-644" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/create-new-mailchimp-audience-id.png 525w, https://www.codeindotnet.com/wp-content/uploads/2022/04/create-new-mailchimp-audience-id-300x32.png 300w" sizes="auto, (max-width: 525px) 100vw, 525px" /></figure>



<br>



<p>The below image confirms Audience has been created via code and the same can be seen in the MailChimp portal.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="830" height="304" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/created-new-mailchimp-audience-id.png" alt="verify the newly created Audience name in the MailChimp portal" class="wp-image-646" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/created-new-mailchimp-audience-id.png 830w, https://www.codeindotnet.com/wp-content/uploads/2022/04/created-new-mailchimp-audience-id-300x110.png 300w, https://www.codeindotnet.com/wp-content/uploads/2022/04/created-new-mailchimp-audience-id-768x281.png 768w" sizes="auto, (max-width: 830px) 100vw, 830px" /></figure>



<p>To see <strong>Audience Id</strong> &#8211; On the same page, scroll down and click on <strong>Setting</strong> &gt;&gt; <strong>Audience name and defaults</strong>. It will navigate to another page and there you can see the newly created audience name &amp; id, see the below screenshots.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="280" height="164" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-setting-audience-defaults.png" alt="Click on MailChimp Audience name and defaults" class="wp-image-790"/></figure>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1008" height="185" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/created-mailchimp-audience-name-id.png" alt="find and get the Audience Id in the MailChimp portal" class="wp-image-786" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/created-mailchimp-audience-name-id.png 1008w, https://www.codeindotnet.com/wp-content/uploads/2022/04/created-mailchimp-audience-name-id-300x55.png 300w, https://www.codeindotnet.com/wp-content/uploads/2022/04/created-mailchimp-audience-name-id-768x141.png 768w" sizes="auto, (max-width: 1008px) 100vw, 1008px" /></figure>



<br>



<h3 class="wp-block-heading" id="Add-subscribers"><strong>2. Add Subscribers</strong></h3>



<p>The Next step is to add subscribers to an audience. </p>



<p><strong><mark style="background-color:rgba(0, 0, 0, 0);color:#d74949" class="has-inline-color">Note:</mark></strong> Subscriber or Member or email id &#8211; all are the same.</p>



<p>The below code shows how to add a member&#8217;s emailId, first &amp; last name. Add it to <strong>MailChimpHelper</strong> class and call this method from the business class.</p>



<button class="c-b-s-f-r" onclick="ctc('div4',this)">Copy code</button>
<br>
<div id="div4"><pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">async</span> Task&lt;Member&gt; MemberAddOrUpdateAsync(<span class="key">string</span> apiKey, <span class="key">string</span> listId, <span class="custkey">SubscribeProperty</span> subscribe)
{
    <span class="com">//To add email address</span>
    <span class="key">var</span> member = <span class="key">new</span> Member { EmailAddress = HttpUtility.HtmlEncode(subscribe.Email.ToLower()), Status = Status.Subscribed };
    <span style="background:#f2f19d;"><span class="key">await</span> <span class="key">new</span> MailChimpManager(apiKey).Members.AddOrUpdateAsync(listId, member);</span>

    <span class="com">//To update First &amp; Last Name</span>
    <span class="key">if</span> (!<span class="key">string</span>.IsNullOrWhiteSpace(subscribe.FirstName))
    {
        member.MergeFields.Add(<span class="str">"FNAME"</span>, HttpUtility.HtmlEncode(subscribe.FirstName));
    }
    <span class="key">if</span> (!<span class="key">string</span>.IsNullOrWhiteSpace(subscribe.LastName))
    {
        member.MergeFields.Add(<span class="str">"LNAME"</span>, HttpUtility.HtmlEncode(subscribe.LastName));
    }

    <span class="key">return</span> <span class="key">await</span> <span class="key">new</span> MailChimpManager(apiKey).Members.AddOrUpdateAsync(listId, member);
}</code></pre></div>



<br>



<p>The below code shows adding more than one subscriber by using <strong>foreach </strong>loop, in business class.</p>



<button class="c-b-s-f-r" onclick="ctc('div5',this)">Copy code</button>
<br>
<div id="div5"><pre class="pchl"><code><span class="key">public</span> <span class="key">async</span> Task AddUpdateMembers()
{
	<span class="com">//Get newly registered users from database</span>
	<span class="key">var</span> newUsers = GetNewUsers();

	<span class="key">var</span> existingAudienceId = <span class="str">"7f7cb00b8f"</span>;

	<span class="key">foreach</span> (<span class="key">var</span> user <span class="key">in</span> newUsers)
	{
		<span class="custkey">SubscribeProperty</span> subscribe = <span class="key">new</span> <span class="custkey">SubscribeProperty</span>
		{
			Email = user.subscribers_id,
			FirstName = user.first_name,
			LastName = user.last_name
		};

		<span class="key">await</span> <span style="background:#f2f19d;">MailChimpHelper.MemberAddOrUpdateAsync(apiKey, existingAudienceId, subscribe);</span>
	}
}</code></pre></div>



<br>



<p>The below screenshot confirms the added or updated <strong>email address, first and last name</strong> via code can be seen in the portal as well.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="719" height="404" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-add-subscriber.png" alt="add subscriber or email to the audience" class="wp-image-796" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-add-subscriber.png 719w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-add-subscriber-300x169.png 300w" sizes="auto, (max-width: 719px) 100vw, 719px" /></figure>



<br>



<p>Additionally, you can specify one or more <strong>tags </strong>to an email address, below are the lines of code to add tags.</p>



<button class="c-b-s-f-r" onclick="ctc('div6',this)">Copy code</button>
<br>
<div id="div6"><pre class="pchl"><code><span class="custkey">Tags</span> tags = <span class="key">new</span> <span class="custkey">Tags</span>();
tags.MemberTags.Add(<span class="key">new</span> <span class="custkey">Tag()</span> { Name = <span class="str">"Promo"</span>, Status = <span class="str">"active"</span> });
<span class="key">await</span> <span class="key">new</span> <span style="background:#f2f19d;">MailChimpManager(apiKey).Members.AddTagsAsync</span>(listId, <span class="str">"abc@gmail.com"</span>, tags);</code></pre></div>



<br>



<p>Code &#8211; To delete a Member</p>



<button class="c-b-s-f-r" onclick="ctc('div7',this)">Copy code</button>
<br>
<div id="div7"><pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">async</span> Task MemberDeleteAsync(<span class="key">string</span> apiKey, <span class="key">string</span> listId, <span class="key">string</span> emailId)
{
	<span class="custkey">IMailChimpManager</span> mc = <span class="key">new</span> <span class="custkey">MailChimpManager</span>(apiKey);
	<span class="key">await</span> <span style="background:#f2f19d;">mc.Members.DeleteAsync(listId, emailId);</span>
}</code></pre></div>



<br>



<p>Code &#8211; To get all Member lists based on ListId(AudienceId)</p>



<button class="c-b-s-f-r" onclick="ctc('div8',this)">Copy code</button>
<br>
<div id="div8"><pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> List&lt;<span class="key">string</span>&gt; GetMembersAsync(<span class="key">string</span> apiKey, <span class="key">string</span> listId)
{
    <span class="key">var</span> members = <span class="key">new</span> <span style="background:#f2f19d;">MailChimpManager(apiKey).Members.GetAllAsync(listId).Result;</span>
    <span class="key">return</span> members.Select(s =&gt; s.EmailAddress).ToList();
}</code></pre></div>



<br>



<h3 class="wp-block-heading" id="Create-Template"><strong>3. Create a Template</strong></h3>



<p>A template is required to create any Campaign. Add the below code in <strong>MailChimpHelper</strong> class which will return the newly created template Id. It is better to save the template Id in the database, for later use.</p>



<button class="c-b-s-f-r" onclick="ctc('div9',this)">Copy code</button>
<br>
<div id="div9"><pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">async</span> Task&lt;<span class="key">int</span>&gt; TemplateCreateAsync(<span class="key">string</span> apiKey, <span class="key">string</span> templateName, <span class="key">string</span> UnlayerContent)
{
    <span class="key">var</span> template = <span class="key">await</span> <span class="key">new</span> <span style="background:#f2f19d;">MailChimpManager(apiKey).Templates.CreateAsync(templateName, <span class="key">string</span>.Empty, UnlayerContent);</span>
    <span class="key">return</span> template.Id;
}</code></pre></div>



<br>



<p class="has-background" style="background-color:#d7eaf8"><strong><mark style="background-color:rgba(0, 0, 0, 0);color:#004173" class="has-inline-color">Important &#8211;</mark></strong> You need to pass full Html content as a string that contains all text, images, buttons, links, and other inputs. Third-party control needs to be integrated if you want to generate such content from your application.</p>



<br>



<p>To check created Template in the portal &#8211; Go to <strong>Campaigns</strong> &gt;&gt; Click on <strong>Email template</strong>, as shown in the below screenshot. </p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="892" height="366" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-create-edit-template.png" alt="create edit email templates in MailChimp from .Net code" class="wp-image-813" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-create-edit-template.png 892w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-create-edit-template-300x123.png 300w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-create-edit-template-768x315.png 768w" sizes="auto, (max-width: 892px) 100vw, 892px" /></figure>



<br>



<h3 class="wp-block-heading" id="Create-Campaign"><strong>4. Create a Campaign</strong></h3>



<p>The final step is to create a Campaign and send emails with the Template(body content) to all the subscribers for an Audience. Add the below code and call it from business class.</p>



<button class="c-b-s-f-r" onclick="ctc('div10',this)">Copy code</button>
<br>
<div id="div10"><pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">async</span> Task&lt;<span class="key">string</span>&gt; CampaignAddAsync(<span class="key">string</span> apiKey, <span class="key">string</span> audienceId, <span class="key">int</span> templateId, <span class="key">string</span> issueTitle, <span class="key">string</span> fromName)
{
    <span class="custkey">MailChimpManager</span> mc = <span class="key">new</span> <span class="custkey">MailChimpManager</span>(apiKey);

    <span class="key">var</span> replyTo = <span class="key">await</span> mc.Lists.GetAsync(audienceId);

    <span class="custkey">Campaign</span> cp = <span class="key">new</span> <span class="custkey">Campaign</span>
    {
        Recipients = <span class="key">new</span> Recipient { ListId = audienceId },
        Settings = <span class="key">new</span> Setting
        {
            TemplateId = templateId,
            FromName = fromName,
            SubjectLine = issueTitle,
            Title = issueTitle,
            ReplyTo = replyTo.CampaignDefaults.FromEmail,

        },
        Type = <span class="custkey">CampaignType</span>.Regular,
    };

    <span class="key">var</span> campaign = <span class="key">await</span> <span style="background:#f2f19d;">mc.Campaigns.AddOrUpdateAsync(cp);</span>

    <span class="key">await</span> <span style="background:#f2f19d;">mc.Campaigns.SendAsync(campaign.Id); </span>

    <span class="key">return</span> campaign.Id;
}</code></pre></div>



<br>



<p>To check it in the portal &#8211; Go to <strong>Campaigns </strong>&gt;&gt; click on <strong>All campaigns</strong> and check the status of the newly created Campaign, as shown in the below screenshot.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="930" height="297" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-create-campaign.png" alt="create a Campaign in MailChimp from .Net code" class="wp-image-819" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-create-campaign.png 930w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-create-campaign-300x96.png 300w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-create-campaign-768x245.png 768w" sizes="auto, (max-width: 930px) 100vw, 930px" /></figure>



<br>



<p>That&#8217;s it, we have seen how to send newsletters or marketing emails by using the MailChimp package in  .Net code. <strong>Points to remember</strong> &#8211; we need an Audience Id, a list of email addresses, and a template Id to create a Campaign.</p>



<br>



<h2 class="wp-block-heading" id="Campaign-Report"><strong>MailChimp Campaign Report</strong></h2>



<p>Once the campaign is sent you can track and <strong>check the report</strong> to know the total number of emails sent, success or failure delivery, opened, subscriber clicks, send time, Unsubscribe &amp; its reason, and more.</p>



<p>I usually use the below lines of code to get the Campaign report, but there are different types of reports available that you can explore.</p>



<button class="c-b-s-f-r" onclick="ctc('div11',this)">Copy code</button>
<br>
<div id="div11"><pre class="pchl"><code><span class="com">// To get sent report</span>
<span class="custkey">IEnumerable</span>&lt;<span class="custkey">SentTo</span>&gt; sendResults = <span class="key">new</span> <span class="custkey">MailChimpManager</span>(apiKey).<span style="background:#f2f19d;">Reports.GetSentToRecipientsAsync(campaignId)</span>.Result.Where(w =&gt; w.Status == <span class="str">"sent"</span>);

<span class="com">// To get report of each email and its activities</span>
<span class="key">var</span> emailActivities = <span class="key">await</span> <span class="key">new</span> <span class="custkey">MailChimpManager</span>(apiKey).<span style="background:#f2f19d;">Reports.GetEmailActivitiesAsync(campaignId);</span>                </code></pre></div>



<p>Debug &#8211; Report screenshots</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="516" height="365" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-sent-report.png" alt="generate MailChimp Campaign Sent report" class="wp-image-834" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-sent-report.png 516w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-sent-report-300x212.png 300w" sizes="auto, (max-width: 516px) 100vw, 516px" /></figure>



<br>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="436" height="541" src="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-email-activities-report.png" alt="generate MailChimp Campaign email activities report" class="wp-image-836" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-email-activities-report.png 436w, https://www.codeindotnet.com/wp-content/uploads/2022/04/mailchimp-email-activities-report-242x300.png 242w" sizes="auto, (max-width: 436px) 100vw, 436px" /></figure>



<br><br><br>



<p>Thanks <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<br>



<div id="PageInAd1"></div>
<script>
fetch('/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br>


<ul class="wp-block-latest-posts__list wp-block-latest-posts"><li><a class="wp-block-latest-posts__post-title" href="https://www.codeindotnet.com/json-validator-beautifier-online-tool/">Validate JSON, Format &amp; Beautify JSON</a></li>
<li><a class="wp-block-latest-posts__post-title" href="https://www.codeindotnet.com/extract-ssn-from-text/">SSN Extractor</a></li>
<li><a class="wp-block-latest-posts__post-title" href="https://www.codeindotnet.com/extract-guid-uuid-from-text/">UUID/GUID Extractor</a></li>
<li><a class="wp-block-latest-posts__post-title" href="https://www.codeindotnet.com/extract-url-from-text/">URL Extractor</a></li>
<li><a class="wp-block-latest-posts__post-title" href="https://www.codeindotnet.com/extract-mac-address-from-text/">MAC Address Extractor</a></li>
</ul>]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/how-to-integrate-mailchimp-v3-0-api-in-dotnet-core-c/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
	</channel>
</rss>
