<?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 - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/dotnet-core/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Sun, 09 Jun 2024 21:38:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>.NET Core - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Send Email in ASP.NET Core using MailKit with Attachments</title>
		<link>https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/</link>
					<comments>https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 17 Oct 2023 02:22:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET 7 mailkit]]></category>
		<category><![CDATA[asp.net core .NET 6]]></category>
		<category><![CDATA[asp.net core 3.1 send email]]></category>
		<category><![CDATA[asp.net core mailkit]]></category>
		<category><![CDATA[asp.net core mailkit tutorial]]></category>
		<category><![CDATA[asp.net core send email]]></category>
		<category><![CDATA[c mailkit send attachment]]></category>
		<category><![CDATA[c# mailkit gmail example]]></category>
		<category><![CDATA[c# mailkit smtp example]]></category>
		<category><![CDATA[email .net5]]></category>
		<category><![CDATA[how to use mailkit in c#]]></category>
		<category><![CDATA[mailkit .net core 3.1]]></category>
		<category><![CDATA[mailkit .net core 5]]></category>
		<category><![CDATA[mailkit attach csvf]]></category>
		<category><![CDATA[mailkit attach doc]]></category>
		<category><![CDATA[mailkit attach excel]]></category>
		<category><![CDATA[mailkit attach html]]></category>
		<category><![CDATA[mailkit attach pdf]]></category>
		<category><![CDATA[mailkit dispose]]></category>
		<category><![CDATA[mailkit embed image]]></category>
		<category><![CDATA[mailkit multiple recipients]]></category>
		<category><![CDATA[mailkit net core]]></category>
		<category><![CDATA[mailkit net core 2]]></category>
		<category><![CDATA[mailkit send attachment]]></category>
		<category><![CDATA[mailkit smtpclient attachment]]></category>
		<category><![CDATA[mailkit vb.net example]]></category>
		<category><![CDATA[mailkit vs smtpclient]]></category>
		<category><![CDATA[mimekit mailmessage]]></category>
		<category><![CDATA[Send Email in ASP.NET Core using MailKit]]></category>
		<category><![CDATA[Send email mailkit attach csvf]]></category>
		<category><![CDATA[Send email mailkit attach doc]]></category>
		<category><![CDATA[Send email mailkit attach excel]]></category>
		<category><![CDATA[Send email mailkit attach html]]></category>
		<category><![CDATA[Send email mailkit attach pdf]]></category>
		<category><![CDATA[Send email mailkit embed image]]></category>
		<category><![CDATA[Send email mailkit smtpclient attachment]]></category>
		<category><![CDATA[smtp .net5 smtp .net 6]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=7600</guid>

					<description><![CDATA[<p>Send Email in ASP.NET Core using MailKit with Attachments Today in this article, we will see how to use MailKit a C# .NET library. We will send emails in ASP.NET Core using MailKit. We will use ASP.NET .NET 6 application examples. We shall also see how to send an email using attachments i.e. we will [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/">Send Email in ASP.NET Core using MailKit with Attachments</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Send Email in ASP.NET Core using MailKit with Attachments</h1>



<figure class="wp-block-image is-resized"><img fetchpriority="high" decoding="async" width="1024" height="404" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-1024x404.jpg" alt="Send Email c# mailkit, MailKit " class="wp-image-7620" style="width:964px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-1024x404.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-300x118.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-768x303.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-1536x606.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-785x310.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap.jpg 1903w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today in this article, we will see how to use <strong>MailKit </strong>a C# .NET library. </p>



<p></p>



<p>We will send emails in ASP.NET Core using MailKit. We will use ASP.NET .NET 6 application examples. </p>



<p></p>



<p>We shall also see how to send an email using attachments i.e. we will attach files like PDF or HTML or Images or Word doc files etc as attachments to emails we are sending to our users.</p>



<p><br>We will cover the below aspects in today&#8217;s article,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-what-is-mailkit">What is MailKit</a></li><li><a href="#aioseo-getting-started">Getting Started</a><ul><li><a href="#aioseo-create-asp-net-core-3-1-or-net-5-0-api">Create ASP.NET Core 3.1 or .NET 6.0 API</a></li></ul></li><li><a href="#aioseo-send-email-in-asp-net-core-using-mailkit---define-mimemessage-structure">Send Email in ASP.NET Core using MailKit &#8211; Define MimeMessage structure</a></li><li><a href="#aioseo-define-smtp-c-mailkit-client">Define SMTP C# MailKit Client</a></li><li><a href="#aioseo-send-email-with-attachment-html-or-jpeg-or-pdf-files">Send Email with Attachment (HTML or . JPEG or . PDF files)</a></li><li><a href="#aioseo-using-mimekit-bodybuilder">Using MimeKit.BodyBuilder</a></li><li><a href="#aioseo-sending-multiple-attachments">Sending multiple Attachments using MailKit</a></li><li><a href="#aioseo-using-gmail-smtp-server">Using Gmail SMTP server with MailKit</a></li><li><a href="#aioseo-retrieving-messages-via-pop3">Retrieving Messages (via Pop3)</a></li><li><a href="#aioseo-retrieving-messages-via-imap">Retrieving Messages (via IMAP )</a></li><li><a href="#aioseo-other-advantages-of-mailkit">Other Advantages of MailKit</a></li><li><a href="#aioseo-differences-between-smtp-vs-mailkit">Differences between SMTP Vs MailKit</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-mailkit"><h3 class="aioseo-faq-block-question">What is MailKit</h3><div class="aioseo-faq-block-answer">
<p>MailKit is a powerful open-source library for .NET that allows developers to easily send, receive, and manipulate email messages. </p>



<p></p>



<p>MailKit provides extensive support for email protocols like <strong>SMTP</strong>, <strong>POP3</strong>, and <strong>IMAP</strong>, making it a comprehensive solution for email communication. </p>



<p></p>



<p>It is commonly used in .NET Core applications for email-related functionalities.</p>



<p></p>



<p> <em>It supports most of the modern protocols</em> and <em>is also optimized for mobile devices</em></p>
</div></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>



<p></p>
</blockquote>



<p> I was looking to build send email functionality as a Service using C# .NET Core 3.1 recently using <strong>MailKit</strong>. </p>



<p></p>



<p>The service’s core functionality was to send emails using the registered <strong>SMTP </strong>server.  </p>



<p></p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>As per Microsoft&nbsp;<strong><a href="https://www.thecodebuzz.com/send-email-in-net-core/" target="_blank" rel="noreferrer noopener" title="Send Email in .NET Core">Send emails using SmtpClient</a>&nbsp;</strong>is good for one-off emails from tools but doesn’t scale to modern requirements of the protocol.  </p>



<p></p>



<p>It’s recommended to use <strong>MailKit&nbsp;</strong>or <strong>MimeKit or </strong>other libraries for any scaled and additional protocol requirements. </p>



<p></p>



<p>So if the requirement is simple enough to send an email <em><strong>SmtpClient</strong>&nbsp;</em>approach will still work for you.  </p>
</blockquote>



<p></p>



<p>I found that .NET Core has full support for email functionality using <strong>MailKit</strong>. </p>



<p></p>



<p>Let&#8217;s send an email from the Gmail mail server (<strong>smtp.gmail.com</strong>) to another domain (<em><a href="mailto:info@thecodebuzz.com" target="_blank" rel="noreferrer noopener"><span class="has-inline-color has-vivid-cyan-blue-color">infoATthecodebuzz.com</span></a></em>) for this article.</p>



<p></p>



<p>I have used my own <strong>Gmail </strong>for sending an email and testing purposes which worked very well after some initial travail.</p>



<p></p>



<p>MailkIt gives <strong>RFC</strong>-compliant <strong>SMTP</strong>, <strong>POP3</strong>, and <strong>IMAP </strong>client implementations.</p>



<p></p>



<p></p>



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



<p></p>



<h4 class="wp-block-heading" id="aioseo-create-asp-net-core-3-1-or-net-5-0-api">Create ASP.NET Core 3.1 or .NET 6.0 API</h4>



<p></p>



<figure class="wp-block-image is-resized"><img decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/mailkit-send-email-asp-net-core-3-1024x575.jpg" alt="embed image in email,MailKit with Attachments" class="wp-image-7602" style="width:738px;height:auto"/></figure>



<p></p>



<p>Please add below <strong><a href="https://www.nuget.org/packages/MailKit/" target="_blank" rel="noreferrer noopener">Nuget </a></strong>packages to the project,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">PM&gt; Install-Package MailKit -Version &lt;version&gt;</pre>



<p></p>



<p><strong>Note</strong>&#8211; Please u<em>se the <strong>latest available </strong>version.</em></p>



<p></p>



<p>We shall be using the POST method for sending out an email. </p>



<p></p>



<p>Please add the below namespace to your file,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">using MailKit.Net.Smtp;


using MimeKit;</pre>



<p></p>



<p>Let’s write the below code for the POST method.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-send-email-in-asp-net-core-using-mailkit---define-mimemessage-structure">Send Email in ASP.NET Core using MailKit &#8211; Define MimeMessage structure</h2>



<p></p>



<p>As a first step please define the <strong>MimeMessage</strong> structure.</p>



<p></p>



<p>A message structure consists of header fields and a body. The body of the message can be plain text or a tree of <strong><em>MIME </em></strong>entities.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
var message = new MimeMessage();
                message.From.Add(new MailboxAddress(&quot;TheCodeBuzz&quot;, &quot;xxxx@gmail.com&quot;));
                message.To.Add(new MailboxAddress(&quot;TheCodeBuzz&quot;, &quot;infoATthecodebuzz.com&quot;));
                message.Subject = &quot;My First Email&quot;;
                message.Body = new TextPart(&quot;plain&quot;)
                {
                    Text = emailData
                };
</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-define-smtp-c-mailkit-client">Define SMTP C# MailKit Client</h2>



<p></p>



<p>Let&#8217;s now define the <strong>SMTP MailKit </strong>client. </p>



<p></p>



<p>We shall pass the <strong><em>MimeMessage </em></strong>object to the Send() API as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using (var client = new MailKit.Net.Smtp.SmtpClient())
          {
                       client.Connect(&quot;smtp.gmail.com&quot;, 587, false);
                        //SMTP server authentication if needed
                        client.Authenticate(&quot;xxxx@gmail.com&quot;, &quot;xxxxx&quot;);
                        client.Send(message);
                        client.Disconnect(true);
                       
          }
</pre></div>


<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong><em>Above </em></strong>GMAIL <strong><em>SMTP </em></strong>using <em><strong>587 </strong></em>as a standards port for the communication.</p>
</blockquote>



<p></p>



<p>Complete the POC example demonstrating the usage as below. </p>



<p></p>



<p>You can very much use the below code in any module as suitable to your <strong><em>layered code structure</em></strong>.</p>



<p></p>



<p><strong><em>Example</em></strong></p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
        &#x5B;HttpPost]
        public ActionResult&lt;IEnumerable&lt;bool&gt;&gt; 
        SendEmail(&#x5B;FromBody] string emailData)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(&quot;TheCodeBuzz&quot;, &quot;xxxx@gmail.com&quot;));
                message.To.Add(new MailboxAddress(&quot;TheCodeBuzz&quot;, &quot;infoATthecodebuzz.com&quot;));
                message.Subject = &quot;My First Email&quot;;
                message.Body = new TextPart(&quot;plain&quot;)
                {
                    Text = emailData
                };
                
                    using (var client = new MailKit.Net.Smtp.SmtpClient())
                    {
                        client.Connect(&quot;smtp.gmail.com&quot;, 587, false);
                        //SMTP server authentication if needed
                        client.Authenticate(&quot;xxxx@gmail.com&quot;, &quot;xxxxx&quot;);
                        client.Send(message);
                        client.Disconnect(true);
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return StatusCode(500, &quot;Error occured&quot;);
            }
            return Ok(true);
        }
</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-send-email-with-attachment-html-or-jpeg-or-pdf-files">Send Email with Attachment (HTML or . JPEG or . PDF files)</h2>



<p></p>



<p>We often need to send an email with custom attachments like PDF, HTML, Images, or Excel files along with custom text bodies.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-mimekit-bodybuilder">Using MimeKit.BodyBuilder</h2>



<p></p>



<p><strong>BodyBuilder</strong> from <strong>MimeKit</strong> is a helper class for building common MIME body structures and provides you the flexibility to build message structures&#8230;</p>



<p></p>



<p>Please see below how to use the <strong>BodyBuilder</strong> class.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-sending-multiple-attachments">Sending multiple Attachments using MailKit</h2>



<p></p>



<p><strong>MimeKit.BodyBuilder</strong> lets you send multiple attachments in email. Please update the above message. </p>



<p></p>



<p>The body which is defined for text only as below for both text and attachments like pdf and jpeg as shown below,</p>



<p></p>



<figure class="wp-block-image size-large"><img decoding="async" width="870" height="318" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg.jpg" alt="send email .NET c# with attachment " class="wp-image-9570" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg.jpg 870w, https://thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg-300x110.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg-768x281.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg-785x287.jpg 785w" sizes="(max-width: 870px) 100vw, 870px" /></figure>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-gmail-smtp-server">Using Gmail SMTP server with MailKit</h2>



<p></p>



<p>For the Gmail SMTP server, the above code worked perfectly for me except I had to update a few security settings as mentioned below. </p>



<p></p>



<p>Initially, you might get the below error,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">”<span class="has-inline-color has-vivid-red-color"> The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. “</span></pre>



<p></p>



<p>Gmail by default prevents you from accessing your e-mail account from external applications. </p>



<p></p>



<p>But you can update your security settings to accept the login from the application. </p>



<p></p>



<p>I got an email from Gmail saying “Critical security alert for your linked Google Account”.</p>



<p></p>



<ul class="wp-block-list">
<li>I had to enable “<strong><em>Allow less secure apps: ON”</em></strong> to make the send email API work properly.</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="2560" height="862" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2.jpg?fit=785%2C264&amp;ssl=1" alt="send email net core" class="wp-image-2986" srcset="https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2.jpg 2560w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-300x101.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-1024x345.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-768x259.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-1536x517.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-2048x690.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-785x264.jpg 785w" sizes="(max-width: 2560px) 100vw, 2560px" /></figure>



<p></p>



<p>Such errors are more due to the policy configured on the SMTP email server. </p>



<p></p>



<p>Make sure you are following the proper settings and policies required for a secure connection to connect to the SMTP server.</p>



<p></p>



<p>Finally, an email popped up successfully in my other domain mail Inbox from my Gmail ID.</p>



<p></p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="490" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-1024x490.jpg" alt="Send Email in ASP.NET Core using MailKit ,email net core 5 MailKit " class="wp-image-7603" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-1024x490.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-300x143.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-768x367.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-1536x734.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-785x375.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server.jpg 1646w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-retrieving-messages-via-pop3">Retrieving Messages (via Pop3)</h2>



<p></p>



<p>Apart from sending emails MaiKit library also provides support for retrieving messages from <strong>pop3 </strong>servers.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-retrieving-messages-via-imap">Retrieving Messages (via IMAP )</h2>



<p></p>



<p><strong><em>MailKit </em></strong>library also provides full support for retrieving messages from <strong>IMAP</strong> servers.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-other-advantages-of-mailkit">Other Advantages of MailKit</h2>



<p></p>



<p><strong>Wide Email Protocol Support:</strong></p>



<p></p>



<p>MailKit provides support for multiple email protocols, including SMTP (for sending emails), POP3 (for receiving emails), and IMAP (for more advanced email operations like folder management and searching).</p>



<p></p>



<p><strong>Open-Source and Cross-Platform:</strong> </p>



<p>MailKit is an open-source library, available under the MIT License, making it freely accessible to developers.</p>



<p></p>



<p><strong>High Performance and Efficient:</strong> </p>



<p></p>



<p>MailKit is designed to be high-performance and efficient, optimized for handling large volumes of email messages. It utilizes asynchronous programming patterns (async/await) to avoid blocking threads and ensure responsiveness in applications.</p>



<p></p>



<p><strong>Extensive MIME Support: </strong></p>



<p></p>



<p>MailKit provides extensive support for MIME (Multipurpose Internet Mail Extensions) and allows developers to work with multipart emails, attachments, inline images, and other MIME-related functionalities.</p>



<p></p>



<p><strong>Secured Email Communication:</strong> </p>



<p></p>



<p>MailKit supports secure communication using SSL/TLS protocols, enabling secure connections to email servers and protecting email communication from eavesdropping or interception.</p>



<p></p>



<p>MailKit is designed to be high-performance and efficient, optimized for handling large volumes of email messages. </p>



<p></p>



<p>It utilizes asynchronous programming patterns (async/await) to avoid blocking threads and ensure responsiveness in applications.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-differences-between-smtp-vs-mailkit">Differences between SMTP Vs MailKit</h2>



<p></p>



<p>Please here to understand the high-level differences between <a href="https://www.thecodebuzz.com/send-email-in-net-core/" target="_blank" rel="noopener" title="How to Send Email in .NET Core – SMTP vs MailKit">SMTP Vs MailKit</a></p>



<p></p>



<p><strong><em>Other references </em></strong>: </p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/send-email-in-net-core/" target="_blank" rel="noreferrer noopener"><strong><em>Send Email using SMTP .NET client</em></strong></a></li>
</ul>



<p></p>



<p></p>



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



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



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



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



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



<p></p>



<p></p>



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



<p></p>



<p>Today in this article we learned how to send an email message using <strong><em>MailKit </em></strong>a .NET open-source library. We understand traditional <strong>SMTPClient</strong> is now obsolete and it&#8217;s recommended to use MailKit or MimeKit for scaled and additional protocol requirements.</p>



<p></p>



<hr>



<p class=""></p>



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




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/">Send Email in ASP.NET Core using MailKit with Attachments</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>C# NPOI &#8211; How to Read and Write Excel files in .NET</title>
		<link>https://thecodebuzz.com/read-and-write-excel-file-in-net-core-using-npoi/</link>
					<comments>https://thecodebuzz.com/read-and-write-excel-file-in-net-core-using-npoi/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 04 Mar 2023 02:14:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[.NET 6 excel export]]></category>
		<category><![CDATA[.net core 3.1 excel export]]></category>
		<category><![CDATA[.net core 5 excel export]]></category>
		<category><![CDATA[.net core 6.0 read excel file]]></category>
		<category><![CDATA[.net core create excel file]]></category>
		<category><![CDATA[.net core excel]]></category>
		<category><![CDATA[.net core excel library]]></category>
		<category><![CDATA[.net core read excel file]]></category>
		<category><![CDATA[best way to read excel file in c#]]></category>
		<category><![CDATA[C# read excel]]></category>
		<category><![CDATA[c# read excel file into datatable]]></category>
		<category><![CDATA[c# read excel file into list]]></category>
		<category><![CDATA[c# read excel file line by line]]></category>
		<category><![CDATA[convert excel to datatable in net core]]></category>
		<category><![CDATA[convert excel to datatable in net core 3.1]]></category>
		<category><![CDATA[convert excel to datatable in net core 5]]></category>
		<category><![CDATA[create Excel .net core 6.0]]></category>
		<category><![CDATA[create excel without msoffice]]></category>
		<category><![CDATA[create xlsx]]></category>
		<category><![CDATA[documentformat.openxml .net core]]></category>
		<category><![CDATA[dotnet core excel]]></category>
		<category><![CDATA[dotnet core read excel file]]></category>
		<category><![CDATA[dotnet excel]]></category>
		<category><![CDATA[epplus export to excel asp.net core]]></category>
		<category><![CDATA[Eppplus]]></category>
		<category><![CDATA[excel to datatable .net core]]></category>
		<category><![CDATA[export datatable to excel]]></category>
		<category><![CDATA[export xlsx]]></category>
		<category><![CDATA[how to read data from excel sheet using c#]]></category>
		<category><![CDATA[how to read excel file in c# console application]]></category>
		<category><![CDATA[how to read excel file in c# windows application]]></category>
		<category><![CDATA[Import and Export excel in .NET Core]]></category>
		<category><![CDATA[import data from excel file to database table in asp.net core]]></category>
		<category><![CDATA[import xlsx]]></category>
		<category><![CDATA[microsoft.office.interop.excel .net core]]></category>
		<category><![CDATA[microsoft.office.interop.excel .net core 3.1]]></category>
		<category><![CDATA[microsoft.office.interop.excel .net core 5]]></category>
		<category><![CDATA[net core 3.1 read excel file]]></category>
		<category><![CDATA[net core 5 read excel file]]></category>
		<category><![CDATA[NPOI]]></category>
		<category><![CDATA[open xml sdk .net core]]></category>
		<category><![CDATA[openxml .net core]]></category>
		<category><![CDATA[openxml excel .net core]]></category>
		<category><![CDATA[openxml excel .net core 3.1]]></category>
		<category><![CDATA[openxml excel .net core 5]]></category>
		<category><![CDATA[OpenXML SDK]]></category>
		<category><![CDATA[read and write excel file in c#]]></category>
		<category><![CDATA[Read csv]]></category>
		<category><![CDATA[Read Data from excel in .NET]]></category>
		<category><![CDATA[Read excel]]></category>
		<category><![CDATA[read excel .net core]]></category>
		<category><![CDATA[read xlsx]]></category>
		<category><![CDATA[read xlsx .NET]]></category>
		<category><![CDATA[Read/Write Excel file in .NET core 6]]></category>
		<category><![CDATA[upload excel in .net 6]]></category>
		<category><![CDATA[upload excel in .net core]]></category>
		<category><![CDATA[upload excel in .net core 5]]></category>
		<category><![CDATA[write xlsx]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=5358</guid>

					<description><![CDATA[<p>C# NPOI &#8211; How to Read and Write Excel files in .NET Today in this article we shall see how to use NPOI to perform Read and Write Excel files in C#.NET Core. In our last post, we saw the usage of OpenXML SDK (open-source SDK from Microsoft) to work with Office Word, Excel, and [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/read-and-write-excel-file-in-net-core-using-npoi/">C# NPOI – How to Read and Write Excel files in .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">C# NPOI &#8211; How to Read and Write Excel files in .NET</h1>



<figure class="is-resized wp-block-image"><img loading="lazy" decoding="async" width="1412" height="622" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/09/Read-write-excel-in-dotnet-core-2.2-npoi.jpg?fit=785%2C346&amp;ssl=1" alt="Excel file in C#.NET Core using NPOI" class="wp-image-5364" srcset="https://thecodebuzz.com/wp-content/uploads/2019/09/Read-write-excel-in-dotnet-core-2.2-npoi.jpg 1412w, https://thecodebuzz.com/wp-content/uploads/2019/09/Read-write-excel-in-dotnet-core-2.2-npoi-300x132.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/09/Read-write-excel-in-dotnet-core-2.2-npoi-1024x451.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/09/Read-write-excel-in-dotnet-core-2.2-npoi-768x338.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/09/Read-write-excel-in-dotnet-core-2.2-npoi-785x346.jpg 785w" sizes="auto, (max-width: 1412px) 100vw, 1412px" /></figure>



<p class="">Today in this article we shall see how to use NPOI to perform Read and Write Excel files in C#.NET Core. </p>



<p class=""></p>



<p class="">In our last post, we saw the usage of<em><strong> </strong></em><a href="https://www.thecodebuzz.com/read-excel-file-in-dotnet-core-2-1/" target="_blank" rel="noreferrer noopener" title="Read and Create/Write Excel file in .NET Core"><em><strong>OpenXML SDK</strong></em> </a>(open-source SDK from Microsoft) to work with Office Word, Excel, and PowerPoint. </p>



<p class=""></p>



<p class="">We also looked at another easy-to-use library called <em><strong><a href="https://www.thecodebuzz.com/read-write-excel-in-dotnet-core-epplus/" target="_blank" rel="noopener" title="EPPlus – How to Read/Write Excel files in C# .NET Core">EPPlus </a></strong></em>too. </p>



<p class=""></p>



<p class="">Today, in this article we shall cover below using <strong><em>NPOI</em></strong>,</p>



<p class=""></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-you-dont-need-microsoft-office">You don&#x27;t need Microsoft Office</a><ul><li><a href="#aioseo-what-is-npoi">What is NPOI</a></li></ul></li><li><a href="#aioseo-getting-started">Getting Started</a></li><li><a href="#aioseo-read-the-content-of-excel-file-using-npoi">Read the content of the Excel file using C# NPOI</a></li><li><a href="#aioseo-export-write-the-data-to-excel-file-using-npoi">Export/Write the data to an Excel file using NPOI</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p class=""></p>



<p class="">Please see the below references if interested to know more about them.</p>



<p class=""></p>



<ul class="has-medium-font-size wp-block-list">
<li class=""><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/read-excel-file-in-dotnet-core-2-1/" target="_blank"><em>Read/Write Excel file .NET Core using OpemXML SDK</em></a></li>
</ul>



<ul class="has-medium-font-size wp-block-list">
<li class=""><em><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/read-write-excel-in-dotnet-core-epplus/" target="_blank">Read/Write Excel file in .NET Core using EPPlus</a> </em></li>
</ul>



<p class=""></p>



<p class="">We shall be looking into one more simple approach to dealing with Office Excel using the <strong><em>NPOI .NET Core Library</em></strong>.</p>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-you-dont-need-microsoft-office">You don&#8217;t need Microsoft Office</h2>



<p class=""></p>



<p class="">Please note that reading and Creating Excel in C# is possible without installing Microsoft Office. Today we will see a possible and easy-to-implement approach.</p>



<p class=""></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-npoi"><h3 class="aioseo-faq-block-question">What is NPOI</h3><div class="aioseo-faq-block-answer">
<p class="">NPOI is an open-source.NET framework library that offers a wide range of APIs for managing Excel documents, making it a great option for developers to automate operations involving spreadsheets. </p>
</div></div>



<p class="">Utilizing NPOI, you can efficiently manipulate data, add formatting, read existing Excel files, and add formulas. </p>



<p class=""></p>



<p class="">It offers a dependable solution for Excel integration in C# applications and is actively maintained and free to use, saving time and resources for developers.</p>



<p class=""></p>



<p class="">It supports several Excel file types, including.xls and.xlsx, providing versatility and compatibility with multiple Excel versions. </p>



<p class=""></p>



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



<p class=""></p>



<p class="">Let’s create a .NET Core project, you can choose any project template. Here we shall use the .<strong>NET Core 3.1 or .NET 6 </strong>Console project.</p>



<p class=""></p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1925" height="491" src="https://i1.wp.com/thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-consoleproject.jpg?fit=785%2C200&amp;ssl=1" alt="NPOI excel read write c#" class="wp-image-5368" srcset="https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-consoleproject.jpg 1925w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-consoleproject-300x77.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-consoleproject-1024x261.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-consoleproject-768x196.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-consoleproject-1536x392.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-consoleproject-785x200.jpg 785w" sizes="auto, (max-width: 1925px) 100vw, 1925px" /></figure>



<p class=""></p>



<p class="">NuGet&#8217;s package name is <strong>NPOI</strong>. </p>



<p class="">Let’s install this package.</p>



<p class=""></p>



<pre class="wp-block-preformatted has-medium-font-size">PM&gt; Install-Package <a href="https://www.nuget.org/packages/NPOI/" target="_blank" rel="noopener" title="">NPOI</a> -Version &lt;version&gt;</pre>



<p class="">OR</p>



<p class=""></p>



<p class="">Please install from Nuget Package Manager,</p>



<p class=""></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="160" src="https://www.thecodebuzz.com/wp-content/uploads/2020/10/excel-read-write-npoi-1024x160.jpg" alt="NPOI Nuget package" class="wp-image-12600" srcset="https://thecodebuzz.com/wp-content/uploads/2020/10/excel-read-write-npoi-1024x160.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/10/excel-read-write-npoi-300x47.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/10/excel-read-write-npoi-768x120.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/10/excel-read-write-npoi-1536x240.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/10/excel-read-write-npoi-2048x320.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2020/10/excel-read-write-npoi-785x123.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class=""></p>



<p class=""><strong>Note</strong>: Please use the latest available version</p>



<p class=""></p>



<p class="">Let’s look at a simple Excel file with the below column and row details. Let’s try to read the file using our <strong><em>NPOI </em></strong>API,</p>



<p class=""></p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1078" height="924" src="https://i2.wp.com/thecodebuzz.com/wp-content/uploads/2019/01/Read-excel-in-dotnet-core-2.1.jpg?fit=785%2C673&amp;ssl=1" alt="excel npoi read " class="wp-image-1502" srcset="https://thecodebuzz.com/wp-content/uploads/2019/01/Read-excel-in-dotnet-core-2.1.jpg 1078w, https://thecodebuzz.com/wp-content/uploads/2019/01/Read-excel-in-dotnet-core-2.1-300x257.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/01/Read-excel-in-dotnet-core-2.1-1024x878.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/01/Read-excel-in-dotnet-core-2.1-768x658.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/01/Read-excel-in-dotnet-core-2.1-607x520.jpg 607w" sizes="auto, (max-width: 1078px) 100vw, 1078px" /></figure>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-read-the-content-of-excel-file-using-npoi"><strong>Read the content of the Excel file using C# <strong>NPOI</strong></strong></h2>



<p class=""></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="">POC example as below. This ready to use API can be used in&nbsp;<strong>.NET Core console, or Test project or ASP.NET Core application</strong>&nbsp;or logic can be modified or improved as per your requirements.</p>
</blockquote>



<p class=""></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
static string ReadExcel()
        {
            DataTable dtTable = new DataTable();
            List&lt;string&gt; rowList = new List&lt;string&gt;();
            ISheet sheet;
            using (var stream = new FileStream(&quot;TestData.xlsx&quot;, FileMode.Open))
            {
                stream.Position = 0;
                XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream);
                sheet = xssWorkbook.GetSheetAt(0);
                IRow headerRow = sheet.GetRow(0);
                int cellCount = headerRow.LastCellNum;
                for (int j = 0; j &lt; cellCount; j++)
                {
                    ICell cell = headerRow.GetCell(j);
                    if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
                    {
                        dtTable.Columns.Add(cell.ToString());
                    } 
                }
                for (int i = (sheet.FirstRowNum + 1); i &lt;= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null) continue;
                    if (row.Cells.All(d =&gt; d.CellType == CellType.Blank)) continue;
                    for (int j = row.FirstCellNum; j &lt; cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                        {
                            if (!string.IsNullOrEmpty(row.GetCell(j).ToString()) &amp;&amp; !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
                            {
                                rowList.Add(row.GetCell(j).ToString());
                            }
                        }
                    }
                    if(rowList.Count&gt;0)
                    dtTable.Rows.Add(rowList.ToArray());
                    rowList.Clear(); 
                }
            }
            return JsonConvert.SerializeObject(dtTable);
        }
</pre></div>


<p class=""></p>



<p class="">After executing the above API, one can easily read all the Excel details.</p>



<p class=""></p>



<ul class="wp-block-list">
<li class="">In the above example, I have used the file “testdata.xlsx” as input. I have kept this file in the output directory bin\Debug\netcoreapp3.1.</li>
</ul>



<p class=""></p>



<ul class="wp-block-list">
<li class="">Also if needed you can keep the file locally like ex.&nbsp;<br><em>string strDoc = @”<strong>C:\Users\Public\Documents\testdata .xlsx</strong>”&nbsp;</em>.</li>
</ul>



<p class=""></p>



<p class="">I am showing the results as JSON out as shown below,</p>



<p class=""></p>



<p class="">One can map the above output details to respective class objects using the mapping logic of their choice. </p>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-export-write-the-data-to-excel-file-using-npoi"><br><strong>Export/Write the data to an Excel file using <strong>NPOI</strong></strong></h2>



<p class=""></p>



<p class="">We shall now look at creating or writing the data into an Excel file.</p>



<p class=""></p>



<p class="">Here is the sample data/object which we want to save as an Excel file.</p>



<p class=""></p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1456" height="341" src="https://i2.wp.com/thecodebuzz.com/wp-content/uploads/2019/01/image-2.png?fit=785%2C184&amp;ssl=1" alt="" class="wp-image-1539" srcset="https://thecodebuzz.com/wp-content/uploads/2019/01/image-2.png 1456w, https://thecodebuzz.com/wp-content/uploads/2019/01/image-2-300x70.png 300w, https://thecodebuzz.com/wp-content/uploads/2019/01/image-2-1024x240.png 1024w, https://thecodebuzz.com/wp-content/uploads/2019/01/image-2-768x180.png 768w, https://thecodebuzz.com/wp-content/uploads/2019/01/image-2-785x184.png 785w" sizes="auto, (max-width: 1456px) 100vw, 1456px" /></figure>



<p class=""></p>



<p class="">I am creating a new Excel file in the same project folder to keep everything simple. (Excel file will get created in the ‘bin’ folder of the project). The complete sample API is as below.</p>



<p class=""></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
static void WriteExcel()
        {
            List&lt;UserDetails&gt; persons = new List&lt;UserDetails&gt;()
            {
                new UserDetails() {ID=&quot;1001&quot;, Name=&quot;ABCD&quot;, City =&quot;City1&quot;, Country=&quot;USA&quot;},
                new UserDetails() {ID=&quot;1002&quot;, Name=&quot;PQRS&quot;, City =&quot;City2&quot;, Country=&quot;INDIA&quot;},
                new UserDetails() {ID=&quot;1003&quot;, Name=&quot;XYZZ&quot;, City =&quot;City3&quot;, Country=&quot;CHINA&quot;},
                new UserDetails() {ID=&quot;1004&quot;, Name=&quot;LMNO&quot;, City =&quot;City4&quot;, Country=&quot;UK&quot;},
           };

            // Lets converts our object data to Datatable for a simplified logic.
            // Datatable is most easy way to deal with complex datatypes for easy reading and formatting.

            DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
            var memoryStream = new MemoryStream();
             
            using (var fs = new FileStream(&quot;Result.xlsx&quot;, FileMode.Create, FileAccess.Write))
            {
                IWorkbook workbook = new XSSFWorkbook();
                ISheet excelSheet = workbook.CreateSheet(&quot;Sheet1&quot;);

                List&lt;String&gt; columns = new List&lt;string&gt;();
                IRow row = excelSheet.CreateRow(0);
                int columnIndex = 0;
               
                foreach (System.Data.DataColumn column in table.Columns)
                {
                    columns.Add(column.ColumnName);
                    row.CreateCell(columnIndex).SetCellValue(column.ColumnName);
                    columnIndex++;
                }

                int rowIndex = 1;
                foreach (DataRow dsrow in table.Rows)
                {
                    row = excelSheet.CreateRow(rowIndex);
                    int cellIndex = 0;
                    foreach (String col in columns)
                    {
                        row.CreateCell(cellIndex).SetCellValue(dsrow&#x5B;col].ToString());
                        cellIndex++;
                    }

                    rowIndex++;
                }
                workbook.Write(fs);
            }

        }

</pre></div>


<p class=""></p>



<p class="">Once you execute  ‘workbook.Write(fs)‘ will save the file to the ‘bin’ folder location. You can modify the location of the generated file as needed.</p>



<p class=""></p>



<p class=""></p>



<p class="">After executing the above API, a new Excel file will be created with the above custom objects transformed into respective Excel Columns and row details as below,</p>



<p class=""></p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1585" height="723" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-file.jpg?fit=785%2C358&amp;ssl=1" alt="C# read excel NPOI " class="wp-image-5360" srcset="https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-file.jpg 1585w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-file-300x137.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-file-1024x467.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-file-768x350.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-file-1536x701.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/09/excel-read-write-npoi-dot-net-core-file-785x358.jpg 785w" sizes="auto, (max-width: 1585px) 100vw, 1585px" /></figure>



<p class=""></p>



<p class="">That’s all, we just learned how to import and export data to/from Excel in a simple way in a .NET Core framework-based application using the NPOI library.</p>



<p class=""></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="">Please visit the <strong><em>GitHub </em></strong>link for the complete code.</p>
</blockquote>



<p class=""></p>



<p class=""><strong>Other References&nbsp;</strong>:</p>



<p class=""></p>



<ul class="has-medium-font-size wp-block-list">
<li class=""><strong><em><a href="https://www.thecodebuzz.com/read-write-excel-in-dotnet-core-epplus/" target="_blank" rel="noreferrer noopener"><span style="text-decoration: underline;">Read/Write Excel file .NET Core using OpemXML SDK</span></a></em></strong></li>
</ul>



<ul class="has-medium-font-size wp-block-list">
<li class=""><strong><em><a href="https://www.thecodebuzz.com/read-write-excel-in-dotnet-core-epplus/" target="_blank" rel="noreferrer noopener"><span style="text-decoration: underline;">Read/Write Excel file in .NET Core using EPPlus</span></a></em></strong></li>
</ul>



<p class=""></p>



<p class="">Are you dealing with any complex scenarios? Please let me know and sound off your comments below!</p>



<p class=""></p>



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



<p class=""></p>



<p class="">The <strong><em>NPOI </em></strong>library provides us with easy control while dealing with the Office  Excel file.  Today we learned, how to import and export data to/from Excel in the .NET Core framework using the <em><strong>NPOI</strong></em> library. </p>



<p class="">The legacy so-called applications like Excel or Word are no more legacy and can be used on any platform using simple libraries like <em><strong>NPOI </strong></em>etc.</p>



<p class=""></p>



<hr>



<p class=""></p>



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




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/read-and-write-excel-file-in-net-core-using-npoi/">C# NPOI – How to Read and Write Excel files in .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/read-and-write-excel-file-in-net-core-using-npoi/feed/</wfw:commentRss>
			<slash:comments>25</slash:comments>
		
		
			</item>
		<item>
		<title>Read CSV files in C# .NET Core with examples</title>
		<link>https://thecodebuzz.com/read-csv-file-in-net-core/</link>
					<comments>https://thecodebuzz.com/read-csv-file-in-net-core/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 01 Mar 2023 11:45:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[asp.net core read csv file]]></category>
		<category><![CDATA[c# csv import]]></category>
		<category><![CDATA[C# CSV parser]]></category>
		<category><![CDATA[c# parse csv string]]></category>
		<category><![CDATA[c# parse csv with quotes]]></category>
		<category><![CDATA[C# read CSV file]]></category>
		<category><![CDATA[c# read csv file into array]]></category>
		<category><![CDATA[c# read csv file into datatable]]></category>
		<category><![CDATA[c# read csv file into list]]></category>
		<category><![CDATA[C# read write csv]]></category>
		<category><![CDATA[csv dotnet core]]></category>
		<category><![CDATA[CSV in .NET Core]]></category>
		<category><![CDATA[CSV parse c#]]></category>
		<category><![CDATA[CSV parser c#]]></category>
		<category><![CDATA[csvhelper]]></category>
		<category><![CDATA[csvhelper prepareheaderformatch]]></category>
		<category><![CDATA[how to read csv file in c# windows application]]></category>
		<category><![CDATA[how to read csv file using c#]]></category>
		<category><![CDATA[net csv parser]]></category>
		<category><![CDATA[parse CSV net Core]]></category>
		<category><![CDATA[Read CSV .NET Core]]></category>
		<category><![CDATA[read csv c# .net core]]></category>
		<category><![CDATA[read csv file c# streamreader]]></category>
		<category><![CDATA[Read CSV file in .NET Core using TextFieldParser]]></category>
		<category><![CDATA[read file .net core]]></category>
		<category><![CDATA[read write csv .NET Core]]></category>
		<category><![CDATA[read write CSV dotnet core]]></category>
		<category><![CDATA[TextFieldParser]]></category>
		<category><![CDATA[textfieldparser .net core]]></category>
		<category><![CDATA[textfieldparser c#]]></category>
		<category><![CDATA[tinycsvparser]]></category>
		<category><![CDATA[upload and read csv file in asp.net c#]]></category>
		<category><![CDATA[upload and read csv file in asp.net core]]></category>
		<category><![CDATA[upload and read csv file in asp.net mvc]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=3673</guid>

					<description><![CDATA[<p>Read CSV files in C# .NET Core with examples Today I am going to talk about a few simple approaches to Read CSV files in C# .NET Core framework. We will cover multiple approaches to dealing with CSV files in C# .NET project using libraries like TinyCSVParser, CsvHelper, or TextFieldParser We will see how to [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/read-csv-file-in-net-core/">Read CSV files in C# .NET Core with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Read CSV files in C# .NET Core with examples</h1>



<figure class="wp-block-image is-resized"><a href="https://www.thecodebuzz.com/read-csv-file-in-net-core/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="1482" height="692" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/05/csv-net-core-read-write.jpg?fit=785%2C366&amp;ssl=1" alt="Read CSV files,TinyCSVParser, CsvHelper or TextFieldParser" class="wp-image-3697" srcset="https://thecodebuzz.com/wp-content/uploads/2019/05/csv-net-core-read-write.jpg 1482w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-net-core-read-write-300x140.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-net-core-read-write-1024x478.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-net-core-read-write-768x359.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-net-core-read-write-785x367.jpg 785w" sizes="auto, (max-width: 1482px) 100vw, 1482px" /></a></figure>



<p>Today I am going to talk about a few simple approaches to Read CSV files in C# .NET Core framework. </p>



<p></p>



<p>We will cover multiple approaches to dealing with CSV files in C# .NET project using libraries like TinyCSVParser, CsvHelper, or TextFieldParser</p>



<p></p>



<p> We will see how to use an easy-to-use parser and convert CSV into JSON or other formats as required.</p>



<p></p>



<p>Today in this article we will cover the following aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting Started</a></li><li><a href="#aioseo-using-csv-parser">Using CSV Parser?</a></li><li><a href="#TinyParser">Read CSV Using TinyCSVParser</a></li><li><a href="#CsvHelper">Using CsvHelper Parser to Read CSV files &#8211; Approach 2</a></li><li><a href="#aioseo-using-textfieldparser-for-csv---approach-3">Using TextFieldParser for CSV  &#8211; Approach 3</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p>It is possible that while dealing with modern frameworks and technologies you will still need to use traditional file systems like <em><strong>CSV(.csv), Excel(.xlsx), Doc(.doc) or Text files(.txt)</strong></em>. </p>



<p></p>



<p>These file systems are popular and useful means of persisting the application data.</p>



<p></p>



<p></p>



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



<p></p>



<p>Let’s create a .NET Core application. </p>



<p></p>



<p>To keep simple I have used the .NET Core console application. </p>



<p></p>



<p>I have used the .NET Core 3.1 version but the below example works in any .NET Core frameworks.</p>



<p></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" width="1019" height="325" src="https://www.thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-3.0-2.jpg" alt="C# CSV parser" class="wp-image-3689" srcset="https://thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-3.0-2.jpg 1019w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-3.0-2-300x96.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-3.0-2-768x245.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-3.0-2-785x250.jpg 785w" sizes="auto, (max-width: 1019px) 100vw, 1019px" /></figure>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-csv-parser"><strong>Using CSV Parser?</strong></h2>



<p></p>



<p>Today in this article, we will cover below simple to use the parser,</p>



<p></p>



<ul class="wp-block-list">
<li><strong><em><a href="#TinyParser" target="_blank" rel="noreferrer noopener">TinyCSVParser</a></em></strong></li>
</ul>



<ul class="wp-block-list">
<li><strong><em><a href="#TinyParser" target="_blank" rel="noreferrer noopener">CsvHelper </a></em></strong></li>
</ul>



<ul class="wp-block-list">
<li><strong><em><a href="#TinyParser" target="_blank" rel="noreferrer noopener">TextFieldParser</a></em></strong></li>
</ul>



<p></p>



<h2 class="wp-block-heading" id="TinyParser"><strong>Read CSV Using TinyCSVParser </strong></h2>



<p></p>



<p><strong><em>TinyCSVParser </em></strong>is one of the simple and lightweight parsers for CSV Reading and parsing. </p>



<p></p>



<p>This package is available through Nuget Manager,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">PM&gt; Install-Package <a href="https://www.nuget.org/packages/TinyCsvParser/" target="_blank" rel="noreferrer noopener">TinyCsvParser</a></pre>



<p></p>



<p>It lets you parse CSV and helps you deserialize the data into proper objects too.</p>



<p></p>



<p>Here is a CSV file with data. Let’s use this file as an example, </p>



<p></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" width="920" height="530" src="https://www.thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-file.jpg" alt="Read CSV files c#" class="wp-image-3696" style="width:453px;height:261px" srcset="https://thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-file.jpg 920w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-file-300x173.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-file-768x442.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/05/csv-reading-net-core-file-785x452.jpg 785w" sizes="auto, (max-width: 920px) 100vw, 920px" /></figure>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
 static void Main(string&#x5B;] args)
        {
            CsvParserOptions csvParserOptions = new CsvParserOptions(true, &#039;,&#039;);
            CsvUserDetailsMapping csvMapper = new CsvUserDetailsMapping();
            CsvParser&lt;userdetails&gt; csvParser = new CsvParser&lt;userdetails&gt;(csvParserOptions, csvMapper);
            var result = csvParser
                         .ReadFromFile(@&quot;TestData.csv&quot;, Encoding.ASCII)
                         .ToList();
            Console.WriteLine(&quot;Name &quot; + &quot;ID   &quot; + &quot;City  &quot; + &quot;Country&quot;);
            foreach (var details in result)
            {
                Console.WriteLine(details.Result.Name + &quot; &quot; + details.Result.ID + &quot; &quot; + details.Result.City + &quot; &quot; + details.Result.Country);
            }
      }

</pre></div>


<p></p>



<p>In the above example below the line does all tricks,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">var result = csvParser.ReadFromFile(@"TestData.csv", Encoding.ASCII).ToList();</pre>



<p></p>



<p>The mapping class that needs to be created based on the CSV file&#8217;s Column and Row details is as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
private class CsvUserDetailsMapping : CsvMapping&lt;Userdetails&gt;
        {
            public CsvUserDetailsMapping()
                : base()
            {
                MapProperty(0, x =&gt; x.ID);
                MapProperty(1, x =&gt; x.Name);
                MapProperty(2, x =&gt; x.City);
                MapProperty(3, x =&gt; x.Country);
            }
        }

</pre></div>


<p></p>



<p>A supporting model entity class <em><strong>UserDetails </strong></em>is as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
 
public class UserDetails
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

</pre></div>


<p></p>



<p>Here is the output on the console,</p>



<p></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" width="1510" height="696" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/05/image-57.png?fit=785%2C362&amp;ssl=1" alt="" class="wp-image-3698" style="width:470px;height:217px" srcset="https://thecodebuzz.com/wp-content/uploads/2019/05/image-57.png 1510w, https://thecodebuzz.com/wp-content/uploads/2019/05/image-57-300x138.png 300w, https://thecodebuzz.com/wp-content/uploads/2019/05/image-57-1024x472.png 1024w, https://thecodebuzz.com/wp-content/uploads/2019/05/image-57-768x354.png 768w, https://thecodebuzz.com/wp-content/uploads/2019/05/image-57-785x362.png 785w" sizes="auto, (max-width: 1510px) 100vw, 1510px" /></figure>



<p></p>



<p><strong><em>TinyCSVParser </em></strong>is a very easy-use and efficient way of handling CSV files in C#.</p>



<p></p>



<br>



<h2 class="wp-block-heading" id="CsvHelper"><strong>Using CsvHelper Parser to Read CSV files &#8211; Approach 2</strong></h2>



<p></p>



<p><strong>Csvhelper </strong>is one of the simple and lightweight most preferred parsers for CSV Reading and writing purposes.  </p>



<p></p>



<p></p>



<p> Please see more details here, </p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/csvhelper-read-csv-files-in-csharp-net-core/" target="_blank" rel="noopener" title="CsvHelper – Read CSV files in C# .NET Core"><strong><em>CsvHelper – Read CSV files in C# .NET Core</em></strong></a></li>
</ul>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-textfieldparser-for-csv---approach-3"><strong>Using TextFieldParser for CSV  &#8211; Approach 3 </strong></h2>



<p></p>



<p><strong><em><a href="https://www.nuget.org/packages/CsvHelper/" target="_blank" rel="noreferrer noopener">TextFieldParser </a></em></strong>is also an easy and simple parser for reading CSV files.  </p>



<p></p>



<p>You don’t really need to use any third-party software etc. as it comes with .NET Core 3.0 + above by default. </p>



<p></p>



<p>Please see more details here,</p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/read-csv-file-in-net-core-textfieldparser/" target="_blank" rel="noreferrer noopener"><strong><em>Read CSV file in .NET Core using TextFieldParser</em></strong></a></li>
</ul>



<p></p>



<p></p>



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



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



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



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



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



<p></p>



<p></p>



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



<p></p>



<p>Today in this post we learned a few techniques for dealing with CSV files including reading or writing in  .NET Core framework-based application. </p>



<p></p>



<hr>



<p class=""></p>



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




<br>



<hr>



<p class=""></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/read-csv-file-in-net-core/">Read CSV files in C# .NET Core with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/read-csv-file-in-net-core/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>RESTFul API Unit Testing &#8211; Best Practices</title>
		<link>https://thecodebuzz.com/restful-api-controller-unit-testing-best-practices/</link>
					<comments>https://thecodebuzz.com/restful-api-controller-unit-testing-best-practices/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 22 Dec 2022 03:55:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[Tips and Guidelines]]></category>
		<category><![CDATA[controller testing]]></category>
		<category><![CDATA[iactionresult unit test]]></category>
		<category><![CDATA[net core controller testing]]></category>
		<category><![CDATA[RESTFul API/Controller Unit Testing]]></category>
		<category><![CDATA[spring boot rest controller unit test example]]></category>
		<category><![CDATA[test 500 internal server code]]></category>
		<category><![CDATA[unit test controller c#]]></category>
		<category><![CDATA[unit test controller spring]]></category>
		<category><![CDATA[unit test HTTP status code]]></category>
		<category><![CDATA[unit test mvc controller actionresult]]></category>
		<category><![CDATA[unit test mvc controller actionresult unit test controller spring]]></category>
		<category><![CDATA[unit test web api controller .net core]]></category>
		<category><![CDATA[unit test web api controller request]]></category>
		<category><![CDATA[unit testing spring mvc controllers example]]></category>
		<category><![CDATA[unit testing web api controllers using moq]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=7166</guid>

					<description><![CDATA[<p>Today in this article, we will learn RESTful API Unit Testing &#8211; Best Practices. The recent popularity of frameworks like RESTful services (WebAPI) is getting huge traction. We must develop robust microservices with a clear focus on TDD ( Test-driven Development) by following basic Unit Testing, Integration Testing, and Functional testing as a whole. Today [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/restful-api-controller-unit-testing-best-practices/">RESTFul API Unit Testing – Best Practices</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<figure class="wp-block-image size-large"><a href="https://www.thecodebuzz.com/restful-api-controller-unit-testing-best-practices/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="1351" height="520" src="https://i1.wp.com/thecodebuzz.com/wp-content/uploads/2019/12/moq-to-mock-asynchronous-method-net-core-unit-tests.jpg?fit=785%2C302&amp;ssl=1" alt="RESTFul API/Controller Unit Testing - Best Practices " class="wp-image-7174" srcset="https://thecodebuzz.com/wp-content/uploads/2019/12/moq-to-mock-asynchronous-method-net-core-unit-tests.jpg 1351w, https://thecodebuzz.com/wp-content/uploads/2019/12/moq-to-mock-asynchronous-method-net-core-unit-tests-300x115.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/12/moq-to-mock-asynchronous-method-net-core-unit-tests-1024x394.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/12/moq-to-mock-asynchronous-method-net-core-unit-tests-768x296.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/12/moq-to-mock-asynchronous-method-net-core-unit-tests-785x302.jpg 785w" sizes="auto, (max-width: 1351px) 100vw, 1351px" /></a></figure>



<p>Today in this article, we will learn RESTful API Unit Testing &#8211; Best Practices.</p>



<p></p>



<p>The recent popularity of frameworks like<strong> RESTful</strong> services (WebAPI) is getting huge traction. </p>



<p></p>



<p>We must develop robust microservices with a clear focus on TDD ( <em><strong>Test-driven Development</strong></em>) by following basic Unit Testing, Integration Testing, and Functional testing as a whole.</p>



<p></p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-a-controller-is-a-class">A Controller is a Class!</a></li><li><a href="#aioseo-verify-http-status-code">Verify HTTP Status Code</a></li><li><a href="#aioseo-verify-api-response-static-checking">Verify API Response &#8211; Static Checking</a></li><li><a href="#aioseo-verify-mocked-extension-invocation">Verify Mocked/Extension invocation</a></li><li><a href="#aioseo-verify-business-exception">Verify Business exception</a></li><li><a href="#aioseo-verify-attributes-for-the-controller-method">Verify Attributes for the Controller method</a></li><li><a href="#aioseo-mark-your-test-method-as-async">Mark your Test method as Async</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p>While performing Unit testing there is always confusion in developers on what is scoped under the Unit Testing.</p>



<p></p>



<p>Today we shall see basic guidelines for WebAPI Controller Unit testing. </p>



<p></p>



<p>These guidelines revolve more around <strong>RESTFul</strong> services built using ASP.NET Core WebAPI project templates. </p>



<p></p>



<p>We shall discuss below things that are important from Controller level Unit Testing.</p>



<p></p>



<ul class="wp-block-list">
<li>Verify Inputs </li>



<li>Verify Controller method <strong>Response</strong></li>



<li>Verify <strong>HTTP Status Code</strong>(static check only, don&#8217;t get confused by the Integration test) </li>



<li>Verify <strong>Mocked method invocation</strong> if any</li>



<li>Verify <strong>Extension method invocation</strong> if any</li>



<li>Verify <strong>Annotation/Attribute</strong> if any </li>
</ul>



<p></p>



<p>Here I am using the XUnit test framework but you can use a test framework of your choice.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-a-controller-is-a-class">A Controller is a Class!</h2>



<p></p>



<p>Before we begin writing unit test cases for the controller, the first thing you should understand is that “<strong>Controller</strong>” is not special when it comes to Unit testing.</p>



<p></p>



<p>The controller is a class like any other class which has members like methods and properties etc.</p>



<p></p>



<p>In Unit Testing, we create an instance of the target class call its method for various inputs, and assert the result as per expectation.</p>



<p></p>



<pre class="wp-block-preformatted">//Arrange
           BooksController service = new BooksController(mockBookClient.Object);

//Act
            var result = await service.GetAsync(document.Id) as ObjectResult;
            var actualtResult = result.Value;</pre>



<p></p>



<p>The only thing we do a bit differently in <strong>Controller unit testing</strong> is that of the REST response assertion additionally. </p>



<p></p>



<p>All you need to do is create an instance of the Controller class and invoke all its methods and verify <strong>I/O</strong></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-verify-http-status-code">Verify HTTP Status Code</h2>



<p></p>



<p>Controller methods always return HTTP responses along with resource details by following the REST principles which should include Model state verification and HTTP Status Code. </p>



<p></p>



<p>Controller methods should be unit tested using assert for REST HTTP Status code. </p>



<p></p>



<p>Use the <strong>HttpStatusCode </strong>enum type to Assert the responses.</p>



<p></p>



<p><strong>Example 1</strong></p>



<p></p>



<pre class="wp-block-preformatted has-cyan-bluish-gray-background-color has-background">Assert.Equal(HttpStatusCode.OK, (HttpStatusCode)result.StatusCode);</pre>



<p></p>



<p><strong>Example 2</strong></p>



<p></p>



<pre class="wp-block-preformatted has-cyan-bluish-gray-background-color has-background"> Assert.IsType&lt;OkObjectResult&gt;(result);</pre>



<p></p>



<p>Above, either way, the Unit test makes our API robust and validates the implementation of the REST principle following HTTP verbs correctly.</p>



<p></p>



<p>Each Controller method should be asserted for all <a rel="noreferrer noopener" aria-label="possible types of HTTP status codes (opens in a new tab)" href="https://www.thecodebuzz.com/return-http-status-codes-asp-net-core/" target="_blank">possible types of HTTP Status codes</a> like,</p>



<p></p>



<p>Commonly assertions should include</p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/return-http-status-codes-asp-net-core/" target="_blank" rel="noreferrer noopener">Status Code – 200 (OK)</a></li>



<li><a href="https://www.thecodebuzz.com/return-http-status-codes-asp-net-core/" target="_blank" rel="noreferrer noopener">Status Code &#8211; 401(Unauthorized)</a></li>



<li><a href="https://www.thecodebuzz.com/return-http-status-codes-asp-net-core/" target="_blank" rel="noreferrer noopener">Status Code -201 &#8211; Created </a></li>



<li><a href="https://www.thecodebuzz.com/return-http-status-codes-asp-net-core/" target="_blank" rel="noreferrer noopener">Status Code – 400 (Bad Request)</a></li>



<li><a href="https://www.thecodebuzz.com/return-http-status-codes-asp-net-core/" target="_blank" rel="noreferrer noopener">Status Code – 500 (InternalServerError )</a></li>



<li>+ Others </li>
</ul>



<p></p>



<p>These assertions will ensure that the Controller method produces proper results.</p>



<p></p>



<p><em>Reference</em>: <a href="https://www.thecodebuzz.com/moq-to-mock-asynchronous-method-net-core-unit-tests/" target="_blank" rel="noreferrer noopener">Asynchronous Method Unit Testing in .NET Core</a></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-verify-api-response-static-checking">Verify API Response &#8211; Static Checking</h2>



<p></p>



<p>If the controller method is returning resources, such resources should be validated for their structure.</p>



<p></p>



<p>The below example has the response cast to the actual type i.e. <strong>Book </strong>to very the schema of returned responses. </p>



<p></p>



<pre class="wp-block-preformatted">//Act
           var result = await service.GetAsync(document.Id) as ObjectResult;
           var actualtResult = result.Value;
//Assert
            Assert.Equal(document.Author, ((Book)actualtResult).Author);
            Assert.Equal(document.BookName, ((Book)actualtResult).BookName);
            Assert.Equal(document.Id, ((Book)actualtResult).Id);</pre>



<p></p>



<ul class="wp-block-list">
<li>This will ensure that the code follows a contract properly when the consumer consumes your API.</li>
</ul>



<ul class="wp-block-list">
<li>This schema assertion will red flag the code while development if there are any breaking changes.</li>
</ul>



<p> Reference: <a href="https://www.thecodebuzz.com/moq-to-mock-asynchronous-method-net-core-unit-tests/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">Asynchronous Method Unit Testing in .NET Core</a> </p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-verify-mocked-extension-invocation">Verify Mocked/Extension invocation</h2>



<p></p>



<p>Always assert if mocked methods are invoked at least once. The mocked method is the dependency that is avoided intentionally to concentrate only on the unit of work in isolation.</p>



<p></p>



<p><strong>Example</strong>:</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1427" height="906" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/12/image-10.png?fit=785%2C498&amp;ssl=1" alt="" class="wp-image-7171" srcset="https://thecodebuzz.com/wp-content/uploads/2019/12/image-10.png 1427w, https://thecodebuzz.com/wp-content/uploads/2019/12/image-10-300x190.png 300w, https://thecodebuzz.com/wp-content/uploads/2019/12/image-10-1024x650.png 1024w, https://thecodebuzz.com/wp-content/uploads/2019/12/image-10-768x488.png 768w, https://thecodebuzz.com/wp-content/uploads/2019/12/image-10-785x498.png 785w" sizes="auto, (max-width: 1427px) 100vw, 1427px" /></figure>



<p></p>



<p>Verifying for the above code if the <strong>GetBooksAsync </strong>method which is a dependency (mocked) is called once.</p>



<p></p>



<pre class="wp-block-preformatted has-cyan-bluish-gray-background-color has-background">mockBookClient.Verify(c =&gt; c.GetBookAsync(It.IsAny&lt;string&gt;()), Times.Once);</pre>



<p></p>



<p> Reference: <a href="https://www.thecodebuzz.com/mongodb-driver-mocking-unit-testing-iasynccursor-async-method-part1/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">Unit Testing Extension Method in ASP.NET Core</a></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-verify-business-exception">Verify Business exception </h2>



<p></p>



<p>API responses are critical as there will be consumers using the same as criteria. One can cross-check if business exception messages are raised appropriately. </p>



<p>Most business exceptions will be based on the HTTP status code giving an indication of the resource state. This static check on the return type will make your code robust.</p>



<p></p>



<p>  Reference: <a href="https://www.thecodebuzz.com/moq-to-mock-asynchronous-method-net-core-unit-tests/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">Asynchronous Method Unit Testing in .NET Core</a>  </p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-verify-attributes-for-the-controller-method">Verify Attributes for the Controller method</h2>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="590" src="https://www.thecodebuzz.com/wp-content/uploads/2020/03/Unit-Testing-Authorize-Attribute-ASP.NET-Core-1-1024x590.jpg" alt="" class="wp-image-8418" srcset="https://thecodebuzz.com/wp-content/uploads/2020/03/Unit-Testing-Authorize-Attribute-ASP.NET-Core-1-1024x590.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/03/Unit-Testing-Authorize-Attribute-ASP.NET-Core-1-300x173.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/03/Unit-Testing-Authorize-Attribute-ASP.NET-Core-1-768x443.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/03/Unit-Testing-Authorize-Attribute-ASP.NET-Core-1-785x452.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/03/Unit-Testing-Authorize-Attribute-ASP.NET-Core-1.jpg 1279w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p>There is absolutely no problem in adding more test cases including <strong>Custom attribute</strong> validation or [<strong>Authorize</strong>] attribute validation within the Unit Test cases.</p>



<p></p>



<p></p>



<p><strong>References</strong>: <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://www.thecodebuzz.com/authorize-attribute-custom-unit-test-xunit-asp-net-core/" target="_blank">Unit Testing Authorize Attribute ASP.NET Core</a></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-mark-your-test-method-as-async">Mark your Test method as Async</h2>



<p></p>



<p>As good <a href="https://www.thecodebuzz.com/async-await-csharp-net-guidelines-and-best-practices/">practice mark your Unit test method as async</a> <strong><em>if Controller methods are Asynchronous</em></strong> in nature. </p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="698" height="351" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/Mark-your-unit-test-as-async-CSharp.jpg" alt="" class="wp-image-9745" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/Mark-your-unit-test-as-async-CSharp.jpg 698w, https://thecodebuzz.com/wp-content/uploads/2020/04/Mark-your-unit-test-as-async-CSharp-300x151.jpg 300w" sizes="auto, (max-width: 698px) 100vw, 698px" /></figure>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Your test cases are a state machine. Your test suite in any form will protect your code from anomalies and breaking changes apart from making new code robust and compatible with existing code. </p>



<p> -TheCodebuzz</p>
</blockquote>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>On the good side of unit test cases, you need not have wait for the integration of different modules ( require in Integration test and real API Test) helping in real-time identifying the breaking changes.</p>
</blockquote>



<p></p>



<p>Most Unit test cases run as you type your code, hence it is easy to be tested or identify breaking changes.</p>



<p>We are in the world of <strong>XP </strong>practices and Continuous Development, Continuous review, and Continuous deployment is the way to go.</p>



<p></p>



<p>Do you have any better suggestions to test the Controller method? Please sound off in your comments below.</p>



<p></p>



<p></p>



<p>That&#8217;s all, Happy Coding!</p>



<p></p>



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



<p></p>



<p>Today in this article, we learned helpful guidelines on <strong>Controller </strong>or <strong>RESTFul </strong>API Unit testing. It&#8217;s important to unit-test all possible scenarios for a Controller to make our API robust.</p>



<p></p>



<hr>



<p class=""></p>



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




<br>



<hr>



<p class=""></p>



<p></p>



<p> </p>



<p></p><p>The post <a href="https://thecodebuzz.com/restful-api-controller-unit-testing-best-practices/">RESTFul API Unit Testing – Best Practices</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/restful-api-controller-unit-testing-best-practices/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>How to Get the Current User in ASP.NET Core</title>
		<link>https://thecodebuzz.com/get-current-user-name-asp-net-core/</link>
					<comments>https://thecodebuzz.com/get-current-user-name-asp-net-core/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 12 Dec 2022 16:18:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[asp net core get logged in user id]]></category>
		<category><![CDATA[asp.net core 3.1 identity get current user id]]></category>
		<category><![CDATA[asp.net core 6 get current user]]></category>
		<category><![CDATA[asp.net core get current user id]]></category>
		<category><![CDATA[asp.net core get current user outside controller]]></category>
		<category><![CDATA[asp.net core get current user windows authentication]]></category>
		<category><![CDATA[asp.net get current user identity]]></category>
		<category><![CDATA[get current user logged net core]]></category>
		<category><![CDATA[get user id asp.net core]]></category>
		<category><![CDATA[get user name net core]]></category>
		<category><![CDATA[get username net core 3.0]]></category>
		<category><![CDATA[how to get current user claims in asp.net identity]]></category>
		<category><![CDATA[log username net core]]></category>
		<category><![CDATA[read prod nam]]></category>
		<category><![CDATA[set httpcontext.current.user .net core]]></category>
		<category><![CDATA[windows authentication ID]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=5840</guid>

					<description><![CDATA[<p>This article explains an easy approach on how to get the Current User in ASP.NET Core. You may find a need to get a logged-in username using your application in the IIS or Cloud-hosted app. One can easily get the current user name from HttpContext in ASP.NET Core provided user details are transferred for the [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/get-current-user-name-asp-net-core/">How to Get the Current User in ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" width="921" height="487" src="https://www.thecodebuzz.com/wp-content/uploads/2019/10/get-the-current-user-in-ASP.NET-Core.jpg" alt="Get the Current User in ASP.NET Core, How to Get the Current User in ASP.NET, httpcontext-current-user-identity-name-is-empty,Using HttpContext in Async Task" class="wp-image-5845" style="aspect-ratio:1.9017857142857142;width:487px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/get-the-current-user-in-ASP.NET-Core.jpg 921w, https://thecodebuzz.com/wp-content/uploads/2019/10/get-the-current-user-in-ASP.NET-Core-300x159.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/get-the-current-user-in-ASP.NET-Core-768x406.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/get-the-current-user-in-ASP.NET-Core-785x415.jpg 785w" sizes="auto, (max-width: 921px) 100vw, 921px" /></figure>



<p>This article explains an easy approach on how to get the Current User in ASP.NET Core. </p>



<p></p>



<p>You may find a need to get a logged-in username using your application in the IIS or Cloud-hosted app.</p>



<p></p>



<p>One can easily get the current user name from <strong><em>HttpContext </em></strong>in ASP.NET Core provided user details are transferred for the given session using cookies or other means. etc.</p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-current-username-in-controller">Using HTTPContext metadata</a><ul><li><a href="#aioseo-getting-current-username-in-controller">Getting Current UserName in Controller</a></li><li><a href="#aioseo-access-current-username-in-repository-or-other-custom-components">Access current UserName in Repository or other Custom Components</a></li></ul></li><li><a href="#aioseo-update-configureservices-in-startup-cs-as-below">Update ConfigureServices() in Startup.cs as below,</a></li><li><a href="#aioseo-getting-username-in-method">Getting UserName in Method</a></li><li><a href="#aioseo-getting-username-in-api-middleware">Getting UserName in API Middleware</a></li><li><a href="#aioseo-if-hosting-in-iis-server-set-authentication-mode-as-windows">If Hosting in IIS Server &#8211; Set Authentication mode as Windows</a></li><li><a href="#aioseo-if-debugging-locally">If Debugging locally</a></li><li><a href="#aioseo-httpcontext-user-identity-name-is-empty">HttpContext.User.Identity.Name is empty</a></li></ul></div>



<p></p>



<p>Below are the basic steps that need to be followed.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-current-username-in-controller">Using HTTPContext metadata </h2>



<p></p>



<p><strong><em>HTTPContext </em></strong>lets you <a href="https://www.thecodebuzz.com/middleware-accessing-config-settings-aspnet-core/">access its metadata configured</a> when the request reaches ASP.NET Core API.</p>



<p></p>



<p>This HttpContext sets the various headers including Username and password etc. </p>



<p></p>



<p>This context however also depends on the type of Authentication and Authorization schemes being used to validate the Users.</p>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-getting-current-username-in-controller">Getting Current UserName in Controller </h3>



<p></p>



<p>Getting UserName in Controller is easy as you can directly access the <strong>HttpContext </strong>object within Controller.</p>



<p>You need to access <em><strong>HttpContext.User.Identity.Name</strong></em> the property to access the username.</p>



<p></p>



<p>Update Get method for the below code,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [4]; title: ; notranslate">
        &#x5B;HttpGet]
        public ActionResult&lt;IEnumerable&lt;string&gt;&gt; Get()
        {
            UserName = HttpContext.User.Identity.Name;
            return Ok(UserName);
        }
</pre></div>


<p></p>



<h3 class="wp-block-heading" id="aioseo-access-current-username-in-repository-or-other-custom-components">Access current UserName in Repository or other Custom Components</h3>



<p></p>



<p><em>Access the current </em><strong><em>Username</em> </strong>in the Repository or other Custom modules using <strong><em>HttpContextAccessor</em></strong>.</p>



<p></p>



<p><strong><em>HttpContextAccessor </em></strong>lets you access HTTPContext and its metadata in any other module.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-update-configureservices-in-startup-cs-as-below">Update ConfigureServices() in Startup.cs as below,</h2>



<p></p>



<p></p>



<p><strong><em> .NET Core 3.1 and Above( .NET 5 or .NET6 </em></strong>)</p>



<p></p>



<p>For the .NET Core version 3.1 and above and lower, please register the service for <strong><em>IHttpContextAccessor</em></strong> as below.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [5]; title: ; notranslate">
 public virtual void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddHttpContextAccessor();

        }
</pre></div>


<p></p>



<p><em><strong>.NET Core 3.0 and lower version</strong></em></p>



<p></p>



<p>For the lower version of .NET Core like .NET Core 2.2 and lower, please register the service for <strong><em>IHttpContextAccessor</em></strong> as below.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
  public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
            
        }
</pre></div>


<p></p>



<p></p>



<p>Dependency Inject (<strong>DI</strong>) interface <em><strong>IHttpContextAccessor </strong></em>in the Constructor as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [3,5,6,7,8,9]; title: ; notranslate">
     

class EmployeeRepository : IEmployeeRepository
      {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public EmployeeRepository( IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
...
      }



</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-username-in-method">Getting UserName in Method</h2>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [3,5,6,7,8,9]; title: ; notranslate">
  

class EmployeeRepository : IEmployeeRepository
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public EmployeeRepository( IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }



</pre></div>


<p></p>



<p></p>



<p>Or Access <em><strong>HttpContext.User.Identity.Name </strong></em>in a method,</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="960" height="174" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/Access-current-Username-in-Repository-or-other-Custom-modules-using-HttpContextAccessor.jpg" alt="get username .net core , get username logged in mvc, get username asp.net core,Get the Current User in ASP.NET Core" class="wp-image-9672" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/Access-current-Username-in-Repository-or-other-Custom-modules-using-HttpContextAccessor.jpg 960w, https://thecodebuzz.com/wp-content/uploads/2020/04/Access-current-Username-in-Repository-or-other-Custom-modules-using-HttpContextAccessor-300x54.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/Access-current-Username-in-Repository-or-other-Custom-modules-using-HttpContextAccessor-768x139.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/Access-current-Username-in-Repository-or-other-Custom-modules-using-HttpContextAccessor-785x142.jpg 785w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-username-in-api-middleware">Getting UserName in API Middleware </h2>



<p></p>



<p>Similarly if needed you can read <em><strong><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/access-httpcontext-in-asp-net-core-guidelines/" target="_blank">UserName in the middleware component</a> </strong></em>by accessing <strong><em>HttpContext</em></strong>.</p>



<p></p>



<p><strong>Note</strong>:</p>



<p></p>



<p>If you are trying to get a user name using the user identity then please follow the below configuration and the set authentication mode as Windows.</p>



<p></p>



<p>Below configuration let HttpContext.Current.User.Identity.Name set using the usernames logged in.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-if-hosting-in-iis-server-set-authentication-mode-as-windows">If Hosting in IIS Server &#8211; Set Authentication mode as Windows</h2>



<p></p>



<p>This is the preferred setting for IIS-hosted services also where <strong><em>anonymousAuthentication </em></strong>needs to be set as <em><strong>false</strong></em>.</p>



<p></p>



<p>And Set the <strong><em>WindowsAuthentication </em></strong>as <em><strong>true</strong></em>.</p>



<p></p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size"><em>"windowsAuthentication": true,
"anonymousAuthentication": false</em>

</pre>



<h2 class="wp-block-heading" id="aioseo-if-debugging-locally">If Debugging locally</h2>



<p></p>



<p>If <em>debugging locally</em> to verify, Please update the <em>launchSettings.json</em> file for the Windows authentication setting as true in the &#8216;iisSettings&#8217; section as below. </p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p> <em>windowsAuthentication&#8221;: true, </em></p>



<p><em>&#8220;anonymousAuthentication&#8221;: false</em> </p>
</blockquote>



<p></p>



<h2 class="wp-block-heading" id="aioseo-httpcontext-user-identity-name-is-empty">HttpContext.User.Identity.Name is empty </h2>



<p></p>



<p>If the above-discussed setting is not followed then you will get <em><strong>HttpContext.User.Identity.Name </strong></em>as empty or null.</p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong><em>Cloud-hosted</em></strong> app Windows authentication will also work if enabled with Windows Authentication using the <strong>Active Directory</strong> (AD group) or by following other security policy with in the enterprise infrastructure which let you sync up your User IDs with Server/Cloud.</p>



<p></p>



<p>Most enterprise Application uses secured cookies and session token details (with the help of <strong><em>redirection </em></strong>from their intranet sites to the cloud hosted web applicaiton) to send the actual user name logged in to an application.</p>
</blockquote>



<p></p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong><em>HttpContext </em></strong>is not threadsafe so please follow the below additional <a href="https://www.thecodebuzz.com/httpcontext-best-practices-in-net-csharp-thread-safe/" target="_blank" rel="noopener" title="">guidelines for its proper usage,</a></p>
</blockquote>



<p></p>



<p><strong>References<em>: </em></strong></p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/httpcontext-best-practices-in-net-csharp-thread-safe/" target="_blank" rel="noreferrer noopener" title=" Getting UserName in Constructor "><em><strong>HttpContext Threadsafety and Usage Guidelines</strong></em></a></li>
</ul>



<p></p>



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



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



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



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



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



<p></p>



<hr>



<p class=""></p>



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




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/get-current-user-name-asp-net-core/">How to Get the Current User in ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/get-current-user-name-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
	</channel>
</rss>
