
<?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>Web API &#8211; CodeInDotNet</title>
	<atom:link href="https://www.codeindotnet.com/category/web-api/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codeindotnet.com</link>
	<description>C# Dot Net Programming tutorial &#38; code examples</description>
	<lastBuildDate>Tue, 02 Apr 2024 06:46:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.codeindotnet.com/wp-content/uploads/2021/04/SiteIcon.png</url>
	<title>Web API &#8211; CodeInDotNet</title>
	<link>https://www.codeindotnet.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Enhancing API Security &#8211; 12 Essential Practices</title>
		<link>https://www.codeindotnet.com/api-security-best-practices/</link>
					<comments>https://www.codeindotnet.com/api-security-best-practices/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 02 Mar 2024 00:57:52 +0000</pubDate>
				<category><![CDATA[Web API]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=6966</guid>

					<description><![CDATA[In today&#8217;s interconnected digital landscape, Application Programming Interfaces (APIs) serve as the backbone of numerous web and mobile applications, enabling seamless communication and data exchange between different systems. However, increased connectivity means there&#8217;s a bigger chance someone could sneak in and get important information without permission. To make sure this doesn&#8217;t happen, it&#8217;s really important [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<p>In today&#8217;s interconnected digital landscape, Application Programming Interfaces (APIs) serve as the backbone of numerous web and mobile applications, enabling seamless communication and data exchange between different systems. However, increased connectivity means there&#8217;s a bigger chance someone could sneak in and get important information without permission. To make sure this doesn&#8217;t happen, it&#8217;s really important to put robust security measures in place for APIs. </p>



<br>



<h2 class="wp-block-heading h2Cust1" id="api-security-12-best-practices"><strong>API Security 12 Best Practices</strong></h2>



<br>



<p>Here are 12 essential tips for securing your APIs:</p>



<ol class="custUl1 wp-block-list">
<li><strong>Use HTTPS</strong>: Always ensure that your API communications are encrypted using HTTPS (Hypertext Transfer Protocol Secure). This encrypts the data transmitted between the client and the server, preventing spying and tampering. <br>For instance, instead of <strong>http://</strong>api.example.com, opt for <strong>https://</strong>api.example.com.</li>



<li><strong>Use OAuth2</strong>: Implement OAuth2, an industry-standard protocol for authorization, to control access to your APIs. OAuth2 allows users to grant third-party applications limited access to their resources without exposing their credentials. <br>For example, popular platforms like Google and Facebook utilize OAuth2 for authentication and authorization.</li>



<li><strong>Use WebAuthn</strong>: Enhance authentication security by incorporating WebAuthn, a web authentication standard that enables passwordless authentication using biometrics or hardware tokens. By adopting WebAuthn, organizations can strengthen user authentication for accessing APIs, reducing the risk of credential-based attacks.</li>



<li><strong>Use Leveled API Keys</strong>: Implement API keys with different levels of access privileges based on user roles and responsibilities. <br>For instance, a read-only API key may restrict users from making modifications to data, whereas an admin API key grants full access rights.</li>



<li><strong>Authorization</strong>: Enforce proper authorization mechanisms to ensure that users can only access the resources they are authorized to use. Role-based access control (RBAC) is a common authorization model where access permissions are assigned based on user roles. <br>For example, an e-commerce API may grant customers permission to view product listings but restricts the ability to place orders to authenticated users.</li>



<li><strong>Rate Limiting</strong>: Protect your APIs from abuse and DoS (Denial of Service) attacks by implementing rate limiting. Set limits on how many requests a client can ask for something within a certain period. <br>For instance, a social media API may enforce rate limits to prevent a single user from making an excessive number of requests in a short period, thereby ensuring fair usage of resources.</li>



<li><strong>API Versioning</strong>: Maintain backward compatibility and smooth transitions by versioning your APIs. Versioning allows developers to introduce changes and enhancements without disrupting existing integrations. <br>For example, Twitter&#8217;s API includes versioning in its endpoints (e.g., /1.1/statuses/home_timeline) to support different API versions concurrently.</li>



<li><strong>Whitelisting</strong>: Define a whitelist of trusted IP addresses or domains that are allowed to access your APIs. Whitelisting helps prevent unauthorized access from unknown sources or malicious actors. <br>For instance, a financial institution may whitelist specific partner organizations to securely exchange financial data via APIs.</li>



<li><strong>Check OWASP API Security Risks</strong>: Regularly assess and mitigate potential security vulnerabilities using the OWASP (Open Web Application Security Project) API Security Top 10 checklist. This comprehensive list identifies common security risks such as injection attacks, broken authentication, and excessive data exposure. By addressing these risks proactively, organizations can strengthen their API security posture.</li>



<li><strong>Use API Gateway</strong>: Implement an API gateway as a centralized entry point for managing, securing, and monitoring API traffic. API gateways provide functionalities such as authentication, authorization, rate limiting, and logging, simplifying API management and enhancing security. <br>For instance, Amazon API Gateway offers built-in features for securing and scaling APIs deployed on AWS.</li>



<li><strong>Error Handling</strong>: Implement robust error handling mechanisms to provide informative error messages without exposing sensitive information. Proper error handling helps developers diagnose and troubleshoot issues efficiently while maintaining security. <br>For example, an eCommerce API may return standardized error codes and messages for common scenarios like invalid input or resource not found.</li>



<li><strong>Input Validation</strong>: Validate and sanitize input data to prevent common security vulnerabilities such as SQL injection and cross-site scripting (XSS). Input validation ensures that only well-formed and legitimate data is processed by the API, reducing the risk of exploitation. <br>For instance, a healthcare API may validate user input to ensure that medical record identifiers comply with specific formats and do not contain malicious content.</li>
</ol>



<p>With these 12 tips, you can strengthen the security of your APIs and protect your systems and data from potential threats and vulnerabilities. Remember, proactive security measures are key to staying ahead of malicious actors and maintaining trust with your users and partners.</p>



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



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



<br>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="540" height="240" src="https://www.codeindotnet.com/wp-content/uploads/2024/03/api-security-12-best-practices.jpg" alt="API Security 12 Best Practices" class="wp-image-6984" srcset="https://www.codeindotnet.com/wp-content/uploads/2024/03/api-security-12-best-practices.jpg 540w, https://www.codeindotnet.com/wp-content/uploads/2024/03/api-security-12-best-practices-300x133.jpg 300w" sizes="(max-width: 540px) 100vw, 540px" /></figure></div>


<style>
.custUl1 {
    padding: 5px !important;
    line-height: 1.8;
}
.custUl1> li{
margin-bottom:15px;
}
</style>



<br><br>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/api-security-best-practices/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Read Excel Cell Values using Open XML in C# .Net Core</title>
		<link>https://www.codeindotnet.com/read-excel-cell-value-from-openxml-net-core-c/</link>
					<comments>https://www.codeindotnet.com/read-excel-cell-value-from-openxml-net-core-c/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 21 Nov 2023 15:46:09 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[documentformat.openxml]]></category>
		<category><![CDATA[import excel to datatable openxml c#]]></category>
		<category><![CDATA[openxml excel c#]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=6164</guid>

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



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



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



<br>



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



<br>



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



<br>



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



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



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



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



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



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



<br><br>



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



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



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



<br><br><br>



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



<br>



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



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

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

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

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



<br>



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



<br><br><br>



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



<br>



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

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

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

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

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

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

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

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

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

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

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

				dt.Rows.Add(dataRow);
			}
		}

	}

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


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



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



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



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



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



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



<br>



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



<br><br>



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



<br>



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



<br>



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



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



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



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



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



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



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



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



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



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



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



<br>



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



<br>



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



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



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



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#step-by-step-guide-to-read-excel-spreadsheet-cell-values-from-open-xml-in-c">Step-by-step Guide to Read Excel Spreadsheet Cell Values from OpenXML in C# </a><ul><li><a href="#install-open-xml-sdk-nuget-package">Install OpenXml SDK Nuget Package</a></li><li><a href="#create-api-to-get-an-excel-file">Create API to get an Excel file</a></li><li><a href="#read-data-from-excel-sheet-using-open-xml-c">Read Data from Excel Sheet using OpenXML &#8211; C#</a></li><li><a href="#testing-upload-read-excel-file">Testing &#8211; Upload &amp; Read Excel file</a></li></ul></li></ul></nav></div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/read-excel-cell-value-from-openxml-net-core-c/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>WordPress Custom Rest API &#8211; Adding Endpoints</title>
		<link>https://www.codeindotnet.com/wordpress-custom-rest-api-plugin-endpoints/</link>
					<comments>https://www.codeindotnet.com/wordpress-custom-rest-api-plugin-endpoints/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 07 Nov 2023 15:19:07 +0000</pubDate>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[wordpress api get posts]]></category>
		<category><![CDATA[wordpress web api endpoint integration]]></category>
		<category><![CDATA[wordpress wp rest api json plugin]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5832</guid>

					<description><![CDATA[Adding WordPress Custom Rest API Plugin Sometimes you prefer to create a custom Rest API in PHP within the context of WordPress to return data in a structured format such as JSON which involves setting up custom routes. Here&#8217;s a step-by-step guide to creating &#38; integrating a basic WordPress Custom REST API in a WordPress [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<br>



<h2 class="wp-block-heading h2Cust1" id="adding-word-press-custom-rest-api-plugin"><strong>Adding WordPress <strong>Custom </strong>Rest API Plugin</strong></h2>



<p class="custp1">Sometimes you prefer to create a custom Rest API in PHP within the context of WordPress to return data in a structured format such as JSON which involves setting up custom routes. Here&#8217;s a step-by-step guide to creating &amp; integrating a basic WordPress Custom REST API in a WordPress plugin.</p>



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#set-up-a-word-press-plugin">Set up a WordPress Plugin</a></li><li><a href="#define-wp-api-route">Define WP API Route:</a></li><li><a href="#create-api-callback-function">Create API Callback Function</a></li><li><a href="#test-your-api-endpoint">Test Your API Endpoint</a><ul><li><a href="#how-to-find-wp-api-endpoints-or-ur-ls">How to find WP API endpoints or URLs?</a></li><li><a href="#test-wp-web-api-get-method">Test WP Web API &#8211; Get Method()</a></li></ul></li><li><a href="#calling-word-press-custom-rest-api-from-javascript">Calling WordPress Custom Rest API from Javascript</a></li></ul></nav></div>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="set-up-a-word-press-plugin"><strong>Set up a WordPress Plugin</strong></h2>



<br>



<p>Go to &#8216;wp-content/plugins&#8217; directory of your WordPress and create a PHP file (e.g., CustomApi.php) to serve as a <strong>main plugin file</strong>. </p>



<div><b><i><u>cpanel &#8211; File Manger:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/custom-wordpress-rest-api-cpanel-folder.jpg" alt="custom wordpress rest api plugin php file"/></figure>



<p>In this example, the plugin folder and PHP file <em>names</em> are the same. You can rename it.</p>



<p>You can follow simple 3 steps to create and activate a Custom Plugin in the WordPress Dashboard in a few minutes, check this link &#8211; <a href="https://www.codeindotnet.com/create-wordpress-custom-plugin-in-3-steps/" target="_blank" rel="noreferrer noopener"><span class="cLink3"><b>How to Create Custom WordPress Plugin: 3 Easy Steps</b></span></a>.</p>



<br>



<div class="note2">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div style="padding-top:0.4375rem">You can use the function.php file but it&#8217;s best practice to use a separate Plugin for Custom API.</div>
</div>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="define-wp-api-route"><strong>Define WP API Route</strong>:</h2>



<br>



<p>In your plugin file, use the <span class="spanHT">add_action</span> function to hook into WordPress and register your custom API route. Here&#8217;s an example of how to add an API route:</p>



<div><b><i><u>.php file:</u></i></b></div>



<pre class="pchl"><code><span class="key">function</span> registe_api_routes() {
    <b>register_rest_route</b>('<span class="str">PublicAPIs/v1</span>', '<span class="str">/GetTop10Items'</span>,
						<span class="key">array</span>('<span class="str">methods</span>' =&gt; '<span class="str">GET</span>', '<span class="str">callback</span>' =&gt; '<span class="str">CallFun_GetTop10Items</span>',)
						);
}

<b>add_action</b>('<span class="str">rest_api_init</span>', '<span class="str">registe_api_routes</span>');

</code></pre>



<br><br>



<div><b><i><u>Parameter Description:</u></i></b></div>



<figure class="wp-block-table"><table><thead><tr><th>Parameters</th><th>Inputs</th></tr></thead><tbody><tr><td>Namespace</td><td>PublicAPIs/v1</td></tr><tr><td>Endpoint</td><td>GetTop10Items (Public URL)<br>https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items</td></tr><tr><td>Method</td><td>Get method</td></tr><tr><td>callback function name</td><td>CallFun_GetTop10Items<br>(Internal method that executes and sends back responses)</td></tr></tbody></table></figure>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="create-api-callback-function"><strong>Create API Callback Function</strong></h2>



<br>



<p>Define the callback function you specified in the <span class="spanHT">register_rest_route</span> for your API route. This function will handle the request and return the data you want to show via the API.</p>



<p class="custp1">In our example, whenever public API is called by an external source then the below code will be executed internally. </p>



<div><b><i><u>.php file:</u></i></b></div>



<pre class="pchl"><code><span class="key">function</span> CallFun_GetTop10Items() {
	<span class="com">// Your API logic here</span>
	<span class="com">// Example:</span>
	$args =  <span class="key">array</span>('showposts' =&gt; 10, 'orderby' =&gt; 'post_date', 'order' =&gt; 'DESC','post_status' =&gt; 'publish');

	$query_result = query_posts($args);

	$postList = [];

	<span class="key">foreach</span> ($query_result as $result) {
	  $postList[] = array( "post_title" =&gt; $result-&gt;post_title, "post_name" =&gt; $result-&gt;post_name);
	}

	<span class="key">return</span> $postList;
	<span class="com">// or</span>
	<span class="com">// return new WP_REST_Response($postList, 200);</span>
}</code></pre>



<br><br><div><b><i><u>.php code file &#8211; screenshots:</u></i></b></div>



<br><div><b><i><u>Method 1:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/cpanel-php-editor-register-wordpress-rest-route.jpg" alt="create wordpress rest api callback function and register routes"/></figure>



<br><div>You can write the same code in a shorter way.</div>



<div><b><i><u>Method 2:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/cpanel-php-editor-register-wordpress-rest-route-2.jpg" alt="create wordpress rest api callback function and register routes method 2"/></figure>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="test-your-api-endpoint"><strong>Test Your API Endpoint</strong></h2>



<br>



<p>You can now access your API endpoint and check if it is working as accepted.</p>



<br>



<h3 class="wp-block-heading" id="how-to-find-wp-api-endpoints-or-ur-ls"><strong>How to find WP API endpoints or URLs?</strong></h3>



<ul class="wp-block-list">
<li>Open the browser and open the <strong>Inspect </strong>element developer tool as well. (press f12 or right-click &amp; click Inspect)</li>



<li>Go to <strong>https://yourdomain.com/wp-json/</strong> to get wp-json list. </li>



<li>Once it is loaded, navigate and go to <strong>routes</strong></li>



<li>expand and go to the path (namespace/endpoint) that is defined in <span class="spanHT">register_rest_route</span> method, that is &#8216;<strong>PublicAPIs/v1/GetTop10Items</strong>&#8216;</li>



<li>Get the API (full URL) as shown in the below screenshot. <br><em><strong>example:</strong></em> https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items</li>
</ul>



<br>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/find-wordpress-api-list-wp-json.jpg" alt="find wp rest api list wp-json"/></figure>



<br><br>



<h3 class="wp-block-heading" id="test-wp-web-api-get-method"><strong>Test WP Web API &#8211; Get Method()</strong></h3>



<p class="custp1">Get API can be executed directly on the browser but for demo purposes, we will use the Postman tool to test our API.</p>



<p>The below screenshot demonstrates that a Get API request sends back a response as a JSON result via Postman tool.</p>



<p><strong><em>Test API:</em></strong> https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items</p>



<div><b><i><u>wordpress api get posts:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/wordpress-rest-api-response-result.jpg" alt="wordpress rest api response result"/></figure>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="calling-word-press-custom-rest-api-from-javascript"><strong>Calling WordPress Custom Rest API from Javascript</strong></h2>



<br>



<p>You can use the <span class="spanHT">fetch</span> method in Javascript to call and get the response from the WordPress Custom Rest API, as demonstrated below.</p>



<pre class="pchl"><code>&lt;script>

document.addEventListener("DOMContentLoaded", LoadLatestPosts);

<span class="key">async function</span> LoadLatestPosts() {

	<span class="key">const</span> response = <span class="key">await</span> fetch('<span class="str" style="background:#fafbbb;">/wp-json/PublicAPIs/v1/GetTop10Items</span>');
	<span class="key">const</span> data = <span class="key">await</span> response.json();

	data.<span class="key">forEach</span>(obj => {
		// your logic
	});

}

&lt;/script></code></pre>



<br><div class="note2">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div style="padding-top:0.375rem">You might get an error if the full URL is given with the domain name, so specify the internal URL in the fetch method as mentioned in the code.</div>
</div>



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



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



<p>for more details check this link: <a href="https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/" target="_blank" rel="noopener"><strong>https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/</strong></a></p>



<style>
.toc-cust{
border:1px solid #add8e6;
padding-top: 15px;
padding-left:15px;
}
.toc-cust h2{
font-weight:bold;
font-size: 1.5rem;
color:#ba3925e3;
}
</style>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/wordpress-custom-rest-api-plugin-endpoints/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Create Custom Exception Filter in .Net Core C#?</title>
		<link>https://www.codeindotnet.com/create-custom-exception-filter-attribute-handler-class/</link>
					<comments>https://www.codeindotnet.com/create-custom-exception-filter-attribute-handler-class/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 04 Oct 2023 19:33:51 +0000</pubDate>
				<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[exceptionfilterattribute .net core web api C#]]></category>
		<category><![CDATA[override OnExceptionAsync]]></category>
		<category><![CDATA[return user-friendly error message in response body]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5547</guid>

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



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



<br>



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



<br>



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



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



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



<br><br><br>



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



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



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



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



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



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

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

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


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

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

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

            ex.HttpContext.Response.StatusCode = 400;  
        }


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

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

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

            ex.HttpContext.Response.StatusCode = 400;
        }

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

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



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



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



<br><br>



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



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



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



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



<br><br>



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



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



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



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



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



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

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



<br><br>



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



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



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



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



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



<br><br>



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



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



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



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



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



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



<br>



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



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

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



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



<br>



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



<br>



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



<br><br>



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



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



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



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



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



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



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



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



<br><br>



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



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



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



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



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



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



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



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



<br><br>



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



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



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



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



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



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



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



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



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



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



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



<p><em><strong>reference:</strong></em> <a href="https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling" target="_blank" rel="noreferrer noopener">web-api-global-error-handling</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/exceptionlogger-vs-exceptionfilter-vs-exceptionhandler-in-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>15 Best Postman Alternatives for API Testing Tools</title>
		<link>https://www.codeindotnet.com/15-best-postman-alternative-api-testing-tools/</link>
					<comments>https://www.codeindotnet.com/15-best-postman-alternative-api-testing-tools/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 24 Sep 2023 14:41:51 +0000</pubDate>
				<category><![CDATA[Web API]]></category>
		<category><![CDATA[best api testing tools]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5487</guid>

					<description><![CDATA[API testing is a crucial part of modern software development, ensuring that your applications communicate effectively and reliably with external services. Postman has long been a go-to tool for API testing, with its user-friendly interface and powerful features. However, there are several excellent alternatives available that offer unique advantages. In this article, we&#8217;ll explore the [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<p>API testing is a crucial part of modern software development, ensuring that your applications communicate effectively and reliably with external services. <a href="https://www.postman.com/" target="_blank" rel="noreferrer noopener"><strong>Postman</strong></a> has long been a go-to tool for API testing, with its user-friendly interface and powerful features. However, there are several excellent alternatives available that offer unique advantages. In this article, we&#8217;ll explore the 15 best Postman alternatives for API testing along with the advantages of each.</p>



<br>



<h2 class="wp-block-heading h2Cust1"><strong>Top 15 API Testing Tools</strong></h2>



<br>



<h2 class="wp-block-heading hLBRed"><strong>1) Insomnia</strong></h2>



<p class="custp1"><strong><a href="https://insomnia.rest/" target="_blank" rel="noreferrer noopener">Insomnia</a></strong> is a free, open-source API testing tool known for its intuitive interface and robust features. It offers features such as auto-completion, code generation, and real-time previews of API responses, making it a strong Postman alternative.</p>



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



<ul class="wp-block-list">
<li>Open-source and free.</li>



<li>User-friendly interface.</li>



<li>Supports GraphQL.</li>



<li>Import and export API definitions.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/insomnia-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <a href="https://insomnia.rest/" target="_blank" rel="noreferrer noopener"><strong>https://insomnia.rest/</strong></a></p>



<br>



<h2 class="wp-block-heading hLBRed"><strong>2) Paw</strong></h2>



<p class="custp1"><strong><a href="https://paw.cloud/" target="_blank" rel="noreferrer noopener">Paw</a></strong> is a macOS-exclusive API testing tool that provides advanced capabilities like dynamic values, authentication, and environment variables. Its clean and intuitive interface appeals to developers and testers alike.</p>



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



<ul class="wp-block-list">
<li>Native macOS app.</li>



<li>Advanced request customization.</li>



<li>Excellent support for OAuth and JWT.</li>



<li>Extensive documentation.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/paw-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://paw.cloud/" target="_blank" rel="noreferrer noopener">https://paw.cloud/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>3) SoapUI</strong></h2>



<p class="custp1"><strong><a href="https://www.soapui.org/" target="_blank" rel="noreferrer noopener">SoapUI</a></strong> is a specialized tool for testing SOAP and REST APIs. It&#8217;s a powerful option for those working in environments where SOAP is still prevalent. It offers features like data-driven testing, security testing, and assertion scripting.</p>



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



<ul class="wp-block-list">
<li>Specialized for SOAP and REST.</li>



<li>Robust data-driven testing.</li>



<li>Supports security testing.</li>



<li>Cross-platform support.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/soap-ui-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://www.soapui.org/" target="_blank" rel="noreferrer noopener">https://www.soapui.org/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>4) Katalon Studio</strong></h2>



<p class="custp1"><strong><a href="https://katalon.com/" target="_blank" rel="noreferrer noopener">Katalon Studio</a></strong> is a comprehensive automation testing solution with API testing capabilities. It&#8217;s designed for end-to-end testing and offers a wide range of integrations with various testing frameworks.</p>



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



<ul class="wp-block-list">
<li>All-in-one testing solution.</li>



<li>GUI-based API testing.</li>



<li>Integration with popular CI/CD tools.</li>



<li>Extensive reporting and analytics.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/katalon-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://katalon.com/" target="_blank" rel="noreferrer noopener">https://katalon.com/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>5) Apigee</strong></h2>



<p class="custp1"><strong><a href="https://docs.apigee.com/" target="_blank" rel="noreferrer noopener">Apigee</a></strong> is a Google Cloud product designed for API management and testing. While it&#8217;s primarily an API management platform, it offers robust API testing capabilities, making it an excellent choice for organizations heavily invested in the Google Cloud ecosystem.</p>



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



<ul class="wp-block-list">
<li>Google Cloud integration.</li>



<li>Scalability and reliability.</li>



<li>Comprehensive API management features.</li>



<li>Security and compliance.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/apigee-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://docs.apigee.com/" target="_blank" rel="noreferrer noopener">https://docs.apigee.com/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>6) Rest-Assured</strong></h2>



<p class="custp1"><a href="https://rest-assured.io/" target="_blank" rel="noreferrer noopener"><strong>Rest-Assured</strong></a> is a Java library for testing REST APIs, making it ideal for developers comfortable with Java. It offers a simple and expressive syntax for API testing and supports both JSON and XML.</p>



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



<ul class="wp-block-list">
<li>Java-based, suitable for Java developers.</li>



<li>Fluent, expressive API testing syntax.</li>



<li>Supports JSON and XML.</li>



<li>Easily integrates with popular testing frameworks.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/rest-assured-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://rest-assured.io/" target="_blank" rel="noreferrer noopener">https://rest-assured.io/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>7) Swagger (OpenAPI)</strong></h2>



<p class="custp1"><strong><a href="https://swagger.io/" target="_blank" rel="noreferrer noopener">Swagger</a></strong>, now known as OpenAPI, is a specification for documenting RESTful APIs. While not a testing tool itself, it&#8217;s a valuable resource for API testing. Tools like Swagger UI and Postwoman use OpenAPI specifications for testing APIs.</p>



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



<ul class="wp-block-list">
<li>Standardized API documentation.</li>



<li>Supports multiple API languages.</li>



<li>Compatible with various API testing tools.</li>



<li>Promotes API consistency.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/swagger-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://swagger.io/" target="_blank" rel="noreferrer noopener">https://swagger.io/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>8) Karate DSL</strong></h2>



<p class="custp1"><strong><a href="https://www.karatelabs.io/" target="_blank" rel="noopener">Karate DSL</a></strong> is an open-source tool for API testing and test automation. It combines API testing and HTTP request mocking capabilities, making it a unique choice for comprehensive API testing.</p>



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



<ul class="wp-block-list">
<li>Built-in HTTP request mocking.</li>



<li>Supports BDD-style testing.</li>



<li>JSON and XML support.</li>



<li>Easy to learn for non-developers.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/karate-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://www.karatelabs.io/" target="_blank" rel="noreferrer noopener">https://www.karatelabs.io/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>9) Talend API Tester</strong></h2>



<p class="custp1"><strong><a href="https://www.talend.com" target="_blank" rel="noreferrer noopener">Talend</a></strong> API Tester is a user-friendly tool for API testing and validation. It&#8217;s designed to simplify the API testing process and offers features like assertions, parameterization, and data-driven testing.</p>



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



<ul class="wp-block-list">
<li>Simplified API testing.</li>



<li>GUI-based interface.</li>



<li>Supports data-driven testing.</li>



<li>Integration with Talend ETL for data transformation.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/talend-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://www.talend.com/" target="_blank" rel="noreferrer noopener">https://www.talend.com/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>10) JMeter</strong></h2>



<p class="custp1"><strong><a href="https://jmeter.apache.org/" target="_blank" rel="noreferrer noopener">Apache JMeter</a></strong> is a popular open-source tool for load testing and performance testing, but it can also be used for API testing. It&#8217;s highly extensible and can simulate heavy loads on your API.</p>



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



<ul class="wp-block-list">
<li>Open-source and free.</li>



<li>Scalable for load testing.</li>



<li>Extensive plugin support.</li>



<li>Supports multiple protocols.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/jmeter-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://jmeter.apache.org/" target="_blank" rel="noreferrer noopener">https://jmeter.apache.org/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>11) Dredd</strong></h2>



<p class="custp1"><strong><a href="https://dredd.org/" target="_blank" rel="noreferrer noopener">Dredd</a></strong> is a language-agnostic HTTP API testing framework that focuses on testing API documentation against its implementation. It ensures that your API endpoints conform to your API blueprint or OpenAPI specification.</p>



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



<ul class="wp-block-list">
<li>Tests API documentation against implementation.</li>



<li>Language-agnostic.</li>



<li>Command-line interface.</li>



<li>Automation-friendly.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/dredd-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://dredd.org/" target="_blank" rel="noreferrer noopener">https://dredd.org/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>12) Tricentis Tosca</strong></h2>



<p class="custp1"><strong><a href="https://www.tricentis.com/" target="_blank" rel="noreferrer noopener">Tricentis Tosca</a></strong> is an enterprise-level test automation platform that includes API testing capabilities. It&#8217;s a comprehensive solution for end-to-end testing, including API testing and UI testing.</p>



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



<ul class="wp-block-list">
<li>Comprehensive test automation platform.</li>



<li>Supports API testing.</li>



<li>Integrates with CI/CD pipelines.</li>



<li>Advanced reporting and analytics.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/tricentis-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://www.tricentis.com/" target="_blank" rel="noreferrer noopener">https://www.tricentis.com/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>13) WireMock</strong></h2>



<p class="custp1"><strong><a href="http://wiremock.org/" target="_blank" rel="noreferrer noopener">WireMock</a></strong> is a flexible HTTP mocking library for API testing. It allows you to simulate HTTP responses from APIs, making it ideal for testing in isolation and during development.</p>



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



<ul class="wp-block-list">
<li>Mocks HTTP responses.</li>



<li>Supports custom response scenarios.</li>



<li>Useful for isolated testing.</li>



<li>Easily integrates with testing frameworks.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/wiremock-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://wiremock.org/" target="_blank" rel="noreferrer noopener">https://wiremock.org/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>14) Runscope</strong></h2>



<p class="custp1"><strong><a href="https://www.runscope.com/" target="_blank" rel="noreferrer noopener">Runscope</a></strong> is an API testing and monitoring platform designed for teams. It offers features like API monitoring, traffic inspection, and integration with various tools and services.</p>



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



<ul class="wp-block-list">
<li>Team collaboration features.</li>



<li>API monitoring capabilities.</li>



<li>Traffic inspection and debugging.</li>



<li>Integrates with CI/CD pipelines.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/runscope-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://www.runscope.com/" target="_blank" rel="noreferrer noopener">https://www.runscope.com/</a></strong></p>



<br><br>



<h2 class="wp-block-heading hLBRed"><strong>15) HttpMaster</strong></h2>



<p class="custp1"><strong><a href="https://www.httpmaster.net/" target="_blank" rel="noreferrer noopener">HttpMaster</a></strong> is a desktop application for API testing and debugging. It offers features like dynamic parameters, data validation, and advanced response data extraction.</p>



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



<ul class="wp-block-list">
<li>User-friendly desktop app.</li>



<li>Supports dynamic parameters.</li>



<li>Data validation and extraction.</li>



<li>Automation through command-line interface.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/api-testing-tools/httpmaster-api-testing-tool.jpg" alt=""/></figure>



<br>



<p><strong><em>Official site:</em></strong> <strong><a href="https://www.httpmaster.net/" target="_blank" rel="noreferrer noopener">https://www.httpmaster.net/</a></strong></p>



<br><br>



<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>popular readings:</i></b></span>
		<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
			<div><b>&#8211; <a href="https://www.codeindotnet.com/validate-azure-active-directory-b2c-jwt-bearer-token/">Validate Azure Active Directory B2C Jwt Bearer Token in .NET Core Web API &#8211; C#</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/jwt-bearer-token-authorization-in-swagger-api/">Test Web API with JWT Bearer Authentication In Swagger &#8211; .Net Core</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/">How to Add Swagger in Web API .net core manually? &#8211; easy guide</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/export-dataset-to-excel-in-c-net-core-openxml/">Export DataSet To Excel in C# .Net Core &#8211; OpenXml</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-use-dynamic-parameters-in-dapper-2-0-in-c-net-core/">How To Use Dynamic Parameters In Dapper 2.0 In C# .Net Core?</a></b></div>

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



<br>



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



<p class="custp1">You have many options when it comes to choosing an API testing tool. Each of the 15 alternatives mentioned above offers unique advantages, catering to different needs and preferences. Whether you prioritize simplicity, scalability, or specialized features, there&#8217;s a Postman alternative that suits your requirements. As the landscape of software development continues to evolve, these tools will remain essential for ensuring the reliability and functionality of your APIs.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/15-best-postman-alternative-api-testing-tools/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Validate Azure Active Directory B2C Jwt Bearer Token in .NET Core Web API &#8211; C#</title>
		<link>https://www.codeindotnet.com/validate-azure-active-directory-b2c-jwt-bearer-token/</link>
					<comments>https://www.codeindotnet.com/validate-azure-active-directory-b2c-jwt-bearer-token/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 11 Sep 2023 17:29:34 +0000</pubDate>
				<category><![CDATA[Web API]]></category>
		<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[azure b2c rest api]]></category>
		<category><![CDATA[AzureAdB2C]]></category>
		<category><![CDATA[b2c jwt .net core api]]></category>
		<category><![CDATA[Token Validation Parameters]]></category>
		<category><![CDATA[Validate IssuerSigning Key]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5058</guid>

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

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



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



<br>



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



<br>



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



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



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



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



<br><br>



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



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



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



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

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

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

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

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

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



<br>



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



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



<br><br>



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



<br><br>



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



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



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

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



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



<br>



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



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



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



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



<br>



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



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



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



<br>



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

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



<br>



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



<style>
.toc-cust{
border:1px solid #add8e6;
padding-top: 15px;
padding-left:15px;
}
.toc-cust h2{
font-weight:bold;
font-size: 1.5rem;
color:#ba3925e3;
}
</style>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/validate-azure-active-directory-b2c-jwt-bearer-token/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Test Web API with JWT Bearer Authentication In Swagger &#8211; .Net Core</title>
		<link>https://www.codeindotnet.com/jwt-bearer-token-authorization-in-swagger-api/</link>
					<comments>https://www.codeindotnet.com/jwt-bearer-token-authorization-in-swagger-api/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 10 Sep 2023 04:38:38 +0000</pubDate>
				<category><![CDATA[Web API]]></category>
		<category><![CDATA[addsecuritydefinition]]></category>
		<category><![CDATA[AddSecurityRequirement]]></category>
		<category><![CDATA[open api swagger jwt C#]]></category>
		<category><![CDATA[securityschemes swagger jwt]]></category>
		<category><![CDATA[swagger jwt token authentication bearer]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5014</guid>

					<description><![CDATA[In this article, we&#8217;ll walk through the steps to configure Swagger in a Web API with JWT Bearer Authentication to provide comprehensive documentation and testing capabilities while ensuring security. Prerequisites Before we look into the configuration process, make sure: 1) You have installed the Swashbuckle NuGet package, which integrates Swagger with your API or .NET [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInAd1"></div>
<script>

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



<p>In this article, we&#8217;ll walk through the steps to configure <a href="https://swagger.io/" target="_blank" rel="noopener"><strong>Swagger </strong></a>in a Web API with JWT Bearer Authentication to provide comprehensive documentation and testing capabilities while ensuring security.</p>



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



<p>Before we look into the configuration process, make sure: <br>1) You have installed the <a class="cLink" href="https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/"><strong>Swashbuckle NuGet package</strong></a>, which integrates Swagger with your API or .NET Core application. <br>2) You should have JWT Bearer Authentication set up in your Web API to validate incoming tokens.</p>



<br>



<h2 class="wp-block-heading" id="step-2-configure-swagger-in-startup-cs"><strong>Configure Swagger with JWT Bearer Authentication</strong></h2>



<p class="custp1">Now, let&#8217;s configure Swagger to work with JWT Bearer Authentication in your .NET Core Web API.</p>



<p>Open your <strong>Startup.cs</strong> file and add the necessary configurations for Swagger in the <strong>ConfigureServices </strong>and <strong>Configure </strong>methods.</p>



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



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


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

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

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

	<span class="com">//To Enable authorization using Swagger (JWT)</span>
	swagger<span style="background:#f2f19d;">.AddSecurityDefinition("Bearer", new <span class="custkey">OpenApiSecurityScheme</span>()</span>
	<span style="background:#f2f19d;">{</span>
		Name = "Authorization",
		Type = <span class="custkey">SecuritySchemeType</span>.ApiKey,
		Scheme = "Bearer",
		BearerFormat = "JWT",
		In = <span class="custkey">ParameterLocation</span>.Header,
		Description = <span class="str">"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\""</span>,
	<span style="background:#f2f19d;">});</span>
	swagger<span style="background:#f2f19d;">.AddSecurityRequirement(new <span class="custkey">OpenApiSecurityRequirement</span></span>
	<span style="background:#f2f19d;">{</span>
		{
			  <span class="key">new</span> <span class="custkey">OpenApiSecurityScheme</span>
				{
					Reference = new <span class="custkey">OpenApiReference</span>
					{
						Type = <span class="custkey">ReferenceType</span>.SecurityScheme,
						Id = "Bearer"
					}
				},
				<span class="key">new</span> string[] {}
		}
	<span style="background:#f2f19d;">});</span>
}


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

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

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



<br><br>



<h2 class="wp-block-heading"><strong>Secure Your API</strong></h2>



<p class="custp1">Make sure your API controllers and actions are protected using JWT Bearer Authentication. You can use the <strong>[Authorize]</strong> attribute on specific controllers or actions that require authentication.</p>



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



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

[Route(<span class="str">"api/[controller]"</span>)]
[ApiController]
<span class="key">public</span> <span class="key">class</span> YourController : ControllerBase
{
    [HttpGet]
    <span style="background:#f2f19d;">[Authorize]</span>
    <span class="key">public</span> IActionResult Get()
    {
        <span class="com">// Your action logic</span>
    }
} </code></pre>



<br><br>



<h2 class="wp-block-heading"><strong>Test Your API with Swagger <strong>JWT Bearer Authentication</strong></strong></h2>



<div style="padding-top: 0.625rem;">With Swagger configured, you can now test your API with JWT Bearer Authentication:</div>



<ol class="ul1 wp-block-list">
<li>Start your .NET Core Web API project.</li>



<li class="custp1">Navigate to the Swagger UI by accessing <span class="spanHT">/swagger</span> in your web application (e.g., http://localhost:5000/swagger).</li>



<li class="custp1">Click on the &#8220;<strong>Authorize</strong>&#8221; button in the top right corner of the Swagger UI.<br><img decoding="async" style="margin-top:0.625rem;" src="https://www.codeindotnet.com/img/1/swagger/swagger-jwt-bearer-token-authorize-button.jpg" alt="swagger jwt bearer token authorize button"><br><br></li>



<li>In the &#8220;<strong>Authorization</strong>&#8221; dialog, enter your JWT token in the following format: <span class="spanHT">Bearer YOUR_JWT_TOKEN</span>.<br><img decoding="async" style="margin-top:0.625rem;" src="https://www.codeindotnet.com/img/1/swagger/swagger-jwt-bearer-token-authorization-dialog.jpg" alt="swagger jwt bearer token authorization dialog"><br><br></li>



<li>Click &#8220;<strong>Authorize</strong>&#8221; to authenticate.</li>



<li class="custp1">Explore the available API endpoints, provide any required input data, and click &#8220;<strong>Execute</strong>&#8221; to test your API.</li>
</ol>



<p>Swagger will include the JWT token in the &#8220;Authorization&#8221; header automatically, allowing you to test the secured endpoints.</p>



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



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

		</div>
	</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/jwt-bearer-token-authorization-in-swagger-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Add Swagger in Web API .net core manually? &#8211; easy guide</title>
		<link>https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/</link>
					<comments>https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 09 Sep 2023 02:35:46 +0000</pubDate>
				<category><![CDATA[Web API]]></category>
		<category><![CDATA[.Net Core]]></category>
		<category><![CDATA[add description to swagger api]]></category>
		<category><![CDATA[openapi]]></category>
		<category><![CDATA[swagger api docs]]></category>
		<category><![CDATA[swagger api documentation]]></category>
		<category><![CDATA[swagger api testing]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=4904</guid>

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

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



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



<br>



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



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



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



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



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



<br>



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



<br>



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



<br>



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



<br>



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



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



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



<br><br>



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



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



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


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

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

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


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

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

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



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



<br><br>



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



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



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



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



<br>



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



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



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



<br><br>



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



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



<br><br>



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



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



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



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



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



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



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



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



<br>



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



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



<br>



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



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



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



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



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

		</div>
	</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/add-swagger-documentation-in-net-core-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Export DataSet To Excel in C# .Net Core &#8211; OpenXml</title>
		<link>https://www.codeindotnet.com/export-dataset-to-excel-in-c-net-core-openxml/</link>
					<comments>https://www.codeindotnet.com/export-dataset-to-excel-in-c-net-core-openxml/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 31 Aug 2022 15:43:48 +0000</pubDate>
				<category><![CDATA[Web API]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=1880</guid>

					<description><![CDATA[In this post, we will see how to convert or export DataSet (DataTable) to an Excel file using OpenXml and C# code (Web API, .Net Core). OpenXML SDK is a free, open-source NuGet package from Microsoft that provides tools to work with Office Word, Excel, and PowerPoint documents programmatically. We will cover, how to: Steps [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>



<p>In this post, we will see how to convert or export DataSet (DataTable) to an Excel file using OpenXml and  C# code (Web API, .Net Core). OpenXML SDK is a free, open-source <a href="https://www.nuget.org/packages/DocumentFormat.OpenXml/" data-type="URL" data-id="https://www.nuget.org/packages/DocumentFormat.OpenXml/" target="_blank" rel="noreferrer noopener nofollow">NuGet</a> package from Microsoft that provides tools to work with Office Word, Excel, and PowerPoint documents programmatically.</p>



<p>We will cover, <strong>how to</strong>:</p>



<ul class="wp-block-list">
<li>Generating one or more Sheets in a single Excel file depending on DataTables in a DataSet</li>



<li>Customizing cell style (Stylesheet): Cell Formats (Fonts, Border, Fill) and Alignments (Wrap Text, Vertical, Horizontal)</li>



<li>Resize each Column&#8217;s width</li>
</ul>



<h2 class="wp-block-heading"><strong>Steps to generate excel sheet</strong></h2>



<br>



<h3 class="wp-block-heading"><strong>1.</strong> Install OpenXml SDK Nuget Package</h3>



<p>Create a new Web API project and add the OpenXml package. </p>



<figure class="wp-block-image size-full"><img decoding="async" width="389" height="63" src="https://www.codeindotnet.com/wp-content/uploads/2022/08/install-open-xml-sdk-nuget-package.png" alt="" class="wp-image-1889" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/08/install-open-xml-sdk-nuget-package.png 389w, https://www.codeindotnet.com/wp-content/uploads/2022/08/install-open-xml-sdk-nuget-package-300x49.png 300w" sizes="(max-width: 389px) 100vw, 389px" /></figure>



<br>



<h3 class="wp-block-heading"><strong>2.</strong> Create API to download excel file</h3>



<p>Add the below Get API method in the Controller class, so that the generated excel file can be downloaded. The Swagger tool will be used to test this API.</p>



<pre class="pchl"><code>[<span class="custkey">HttpGet</span>]
<span class="key">public</span> <span class="custkey">IActionResult</span> DownloadExcelFile()
{
	<span class="custkey">DataSet</span> dataSet = <span class="key">new</span> <span class="custkey">DataSet</span>();
	<span class="com">//Configure DB connection string in appsetting.json</span>
	<span class="key">using</span> (<span class="custkey">SqlConnection</span> connection = <span class="key">new</span> <span class="custkey">SqlConnection</span>(_conn))
	{
		<span class="com">/* for multi Sheet either enter multiple 'Select' statement as inline query
		or get multiple result set from Stored Procedure from DB*/</span>
		<span class="custkey">SqlDataAdapter</span> adapter = <span class="key">new</span> <span class="custkey">SqlDataAdapter</span>
		{
			SelectCommand = <span class="key">new</span> <span class="custkey">SqlCommand</span>(<span class="str">"Select * from Products"</span>, connection)
		};
		adapter.Fill(dataSet);
	}
	<span class="key">return</span> File(<span style="background:#f2f19d;"><span class="custkey">Helper</span>.ExportToExcelDownload(dataSet)</span>, <span class="str">"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"</span>, <span class="str">"<strong>YourFileName</strong>.xls"</span>);
} </code></pre>



<br>



<h3 class="wp-block-heading"><strong>3.</strong> Export to Excel C# Code</h3>



<p>Create a static class called &#8220;Helper.cs&#8221; and add a static method to generate one or multiple sheets in the excel file from DataSet. <br><strong>Simply, copy &amp; paste the entire code</strong> given below. That&#8217;s it, done. </p>



<p>Just call <mark style="background-color:#f2f19d" class="has-inline-color">ExportToExcelDownload()</mark> method and pass the DataSet result as input. It will create one or more Sheets based on the number of DataTables in the DataSet and return the fully formed Excel file as bytes.</p>



<p class="has-background" style="background-color:#e3e7ea"><a href="https://www.codeindotnet.com/sfiles/dataset-to-excel-csharp.rar" data-type="URL" data-id="https://www.codeindotnet.com/sfiles/dataset-to-excel-csharp.rar">Download this Project</a> (configure DB and inline query before running this project). <br>Also, read <a href="#StyleIndex" data-type="internal" data-id="#StyleIndex">how to change the Cell format</a> &#8211; explained below. </p>



<br>



<p>Make sure all the necessary namespaces are added. <br><a href="#SwaggerOutput" data-type="internal" data-id="#SwaggerOutput">Scroll down to the output screenshot</a></p>



<pre class="pchl"><code><span class="key">using</span> DocumentFormat.OpenXml;
<span class="key">using</span> DocumentFormat.OpenXml.Packaging;
<span class="key">using</span> DocumentFormat.OpenXml.Spreadsheet;
<span class="key">using</span> System;
<span class="key">using</span> System.Data;
<span class="key">using</span> System.Globalization;
<span class="key">using</span> System.IO; </code></pre>



<pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">class</span> <span class="custkey">Helper</span>
{
	<span class="key">private</span> <span class="key">const</span> <span class="key">string</span> noRecordsToDisplay = <span class="str">"No records to display"</span>;
	
	<span class="key">public</span> <span class="key">static</span> <span class="key">byte</span>[] ExportToExcelDownload(<span class="custkey">DataSet</span> dataSet)
	{
		<span class="key">byte</span>[] byteResult = <span class="key">null</span>;
		<span class="key">if</span> (dataSet == <span class="key">null</span>) { <span class="key">return</span> byteResult; }

		<span class="key">if</span> (dataSet.Tables.Count &gt; 0)
		{
			<span class="key">using</span> (<span class="custkey">MemoryStream</span> stream = <span class="key">new</span> <span class="custkey">MemoryStream</span>())
			{
				<span class="key">using</span> (<span class="custkey">SpreadsheetDocument</span> spreadsheetDocument = <span class="custkey">SpreadsheetDocument</span>.Create(stream, <span class="custkey">SpreadsheetDocumentType</span>.Workbook))
				{
					<span class="com">// Add a WorkbookPart to the document.</span>
					<span class="custkey">WorkbookPart</span> workbookpart = AddWorkbookPart(spreadsheetDocument);
					AddSheet(spreadsheetDocument, <span class="key">out</span> <span class="custkey">Sheets</span> sheets, <span class="key">out</span> <span class="key">uint</span> currentSheetID);
					AddNewPartStyle(workbookpart);

					<span class="key">int</span> rowIndexCount = 1;

					<span class="key">foreach</span> (<span class="custkey">DataTable</span> dt <span class="key">in</span> dataSet.Tables)
					{
						<span class="com">// Add a WorksheetPart to the WorkbookPart.</span>
						<span class="custkey">WorksheetPart</span> worksheetPart = workbookpart.AddNewPart&lt;<span class="custkey">WorksheetPart</span>&gt;();
						worksheetPart.Worksheet = <span class="key">new</span> <span class="custkey">Worksheet</span>();
						<span class="custkey">Columns</span> columns = SetDefaultColumnWidth();
						worksheetPart.Worksheet.Append(columns);

						<span class="custkey"><span class="custkey">SheetData</span></span> sheetData = <span class="key">new</span> <span class="custkey"><span class="custkey">SheetData</span></span>();
						worksheetPart.Worksheet.AppendChild(sheetData);

						<span class="com">// Append a new worksheet and associate it with the workbook.</span>
						<span class="custkey">Sheet</span> sheet = <span class="key">new</span> <span class="custkey">Sheet</span>()
						{
							Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
							SheetId = currentSheetID,
							Name = <span class="key">string</span>.IsNullOrWhiteSpace(dt.TableName) ? <span class="str">"Sheet"</span> + currentSheetID : dt.TableName
						};

						<span class="key">if</span> (dt.Rows.Count == 0)
						{
							<span class="com">//if table rows count is 0, create Excel Sheet with default message</span>
							CreateDefaultWithMessage(rowIndexCount, sheetData);
						}
						<span class="key">else</span>
						{
							<span class="key">int</span> numberOfColumns = dt.Columns.Count;
							<span class="key">string</span>[] excelColumnNames = <span class="key">new string</span>[numberOf<span class="custkey">Columns</span>];

							<span class="com">//Create Header</span>
							<span class="custkey">Row</span> SheetrowHeader = CreateHeader(rowIndexCount, dt, numberOfColumns, excelColumnNames);
							sheetData.Append(SheetrowHeader);
							++rowIndexCount;

							<span class="com">//Create Body</span>
							rowIndexCount = CreateBody(rowIndexCount, dt, sheetData, excelColumnNames);
						}

						sheets.Append(sheet);

						++currentSheetID;

						rowIndexCount = 1;
					}

					workbookpart.Workbook.Save();

					<span class="com">// Close the document.</span>
					<span class="com">//spreadsheetDocument.Close();</span>

				}

				stream.Flush();
				stream.Position = 0;

				byteResult = <span class="key">new byte</span>[stream.Length];
				stream.Read(byteResult, 0, byteResult.Length);
			}
		}
		<span class="key">return</span> byteResult;
	}

	<span class="com">//Customize column width</span>
	<span class="key">private</span> <span class="key">static</span> <span class="custkey">Columns</span> SetDefaultColumnWidth()
	{
		<span class="custkey">Columns</span> columns = <span class="key">new</span> <span class="custkey">Columns</span>();
		<span class="com">//width of 1st Column</span>
		columns.Append(<span class="key">new</span> Column() { Min = 1, Max = 1, Width = 25, CustomWidth = <span class="key">true</span> });
		<span class="com">//with of 2st Column</span>
		columns.Append(<span class="key">new</span> Column() { Min = 2, Max = 2, Width = 50, CustomWidth = <span class="key">true</span> });
		<span class="com">//set column width from 3rd to 400 columns</span>
		columns.Append(<span class="key">new</span> Column() { Min = 3, Max = 400, Width = 10, CustomWidth = <span class="key">true</span> });
		<span class="key">return</span> columns;
	}

	<span class="key">private</span> <span class="key">static</span> <span class="key">void</span> AddNewPartStyle(<span class="custkey">WorkbookPart</span> workbookpart)
	{
		<span class="custkey">WorkbookStylesPart</span> stylePart = workbookpart.AddNewPart&lt;<span class="custkey">WorkbookStylesPart</span>&gt;();
		stylePart.Stylesheet = GenerateStylesheet();
		stylePart.Stylesheet.Save();
	}

	<span class="key">private</span> <span class="key">static</span> <span class="key">void</span> AddSheet(<span class="custkey">SpreadsheetDocument</span> spreadsheetDocument, <span class="key">out</span> <span class="custkey">Sheets</span> sheets, <span class="key">out</span> <span class="key">uint</span> currentSheetID)
	{
		sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(<span class="key">new</span> <span class="custkey">Sheets</span>());
		currentSheetID = 1;
	}

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">WorkbookPart</span> AddWorkbookPart(<span class="custkey">SpreadsheetDocument</span> spreadsheetDocument)
	{
		<span class="custkey">WorkbookPart</span> workbookpart = spreadsheetDocument.AddWorkbookPart();
		workbookpart.Workbook = <span class="key">new</span> <span class="custkey">Workbook</span>();
		<span class="key">return</span> workbookpart;
	}

	<span class="key">private</span> <span class="key">static</span> <span class="key">void</span> CreateDefaultWithMessage(<span class="key">int</span> rowIndexCount, <span class="custkey"><span class="custkey">SheetData</span></span> sheetData)
	{
		<span class="custkey">Row</span> Sheetrow = <span class="key">new</span> <span class="custkey">Row</span>() { RowIndex = <span class="custkey">Convert</span>.ToUInt32(rowIndexCount) };
		<span class="custkey">Cell</span> cellHeader = <span class="key">new</span> <span class="custkey">Cell</span>() { CellReference = <span class="str">"A1"</span>, CellValue = <span class="key">new</span> <span class="custkey">CellValue</span>(noRecordsToDisplay), DataType = <span class="custkey">CellValues</span>.String };
		cellHeader.StyleIndex = 1;

		Sheetrow.Append(cellHeader);
		sheetData.Append(Sheetrow);
	}

	<span class="key">private</span> <span class="key">static</span> <span class="key">int</span> CreateBody(<span class="key">int</span> rowIndexCount, <span class="custkey">DataTable</span> dt, <span class="custkey"><span class="custkey">SheetData</span></span> sheetData, <span class="key">string</span>[] excelColumnNames)
	{
		<span class="key">for</span> (<span class="key">int</span> i = 0; i &lt; dt.Rows.Count; i++)
		{
			<span class="custkey">Row</span> Sheetrow = <span class="key">new</span> <span class="custkey">Row</span>() { RowIndex = <span class="custkey">Convert</span>.ToUInt32(rowIndexCount) };
			<span class="key">for</span> (<span class="key">int</span> j = 0; j &lt; dt.Columns.Count; j++)
			{
				<span class="com">// insert value in cell with dataType (String, Int, decimal, datatime)</span>
				Sheetrow.Append(GetCellWithDataType(excelColumnNames[j] + rowIndexCount, dt.Rows[i][j], dt.Columns[j].DataType));
			}
			sheetData.Append(Sheetrow);
			++rowIndexCount;
		}

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

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">Row</span> CreateHeader(<span class="key">int</span> rowIndexCount, <span class="custkey">DataTable</span> dt, <span class="key">int</span> numberOfColumns, <span class="key">string</span>[] excelColumnNames)
	{
		<span class="custkey">Row</span> SheetrowHeader = <span class="key">new</span> <span class="custkey">Row</span>() { RowIndex = <span class="custkey">Convert</span>.ToUInt32(rowIndexCount) };
		<span class="key">for</span> (<span class="key">int</span> n = 0; n &lt; numberOfColumns; n++)
		{
			excelColumnNames[n] = GetExcelColumnName(n);

			<span class="custkey">Cell</span> cellHeader = <span class="key">new</span> <span class="custkey">Cell</span>() { CellReference = excelColumnNames[n] + rowIndexCount, CellValue = <span class="key">new</span> <span class="custkey">CellValue</span>(dt.Columns[n].ColumnName), DataType = <span class="custkey">CellValues</span>.String };
			cellHeader.StyleIndex = 2;
			SheetrowHeader.Append(cellHeader);
		}

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

	<span class="key">private</span> <span class="key">static</span> <span class="key">string</span> GetExcelColumnName(<span class="key">int</span> columnIndex)
	{
		<span class="key">if</span> (columnIndex &lt; 26)
		{
			<span class="key">return</span> ((<span class="key">char</span>)('A' + columnIndex)).ToString();
		}

		<span class="key">char</span> firstChar = (<span class="key">char</span>)('A' + (columnIndex / 26) - 1);
		<span class="key">char</span> secondChar = (<span class="key">char</span>)('A' + (columnIndex % 26));

		<span class="key">return string</span>.Format(<span class="custkey">CultureInfo</span>.CurrentCulture, <span class="str">"{0}{1}"</span>, firstChar, secondChar);
	}

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">Stylesheet</span> GenerateStylesheet()
	{
		<span class="custkey">Fonts</span> fonts = GenerateFonts();
		<span class="custkey">Fills</span> fills = GenerateFills();
		<span class="custkey">Borders</span> borders = GenerateBorders();
		<span class="custkey">CellFormats</span> cellFormats = GenerateCellFormats();
		<span class="custkey">Column</span> column = GenerateColumnProperty();
		<span class="custkey">Stylesheet</span> styleSheet = <span class="key">new</span> <span class="custkey">Stylesheet</span>(fonts, fills, borders, cellFormats, column);

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

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">Column</span> GenerateColumnProperty()
	{
		<span class="key">return</span> <span class="key">new</span> <span class="custkey">Column</span>
		{
			Width = 100,
			CustomWidth = <span class="key">true</span>
		};
	}

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">CellFormats</span> GenerateCellFormats()
	{
		<span class="custkey">CellFormats</span> cellFormats = <span class="key">new</span> <span class="custkey">CellFormats</span>(
			<span class="com">// default - Cell StyleIndex = 0 </span>
			<span class="key">new</span> <span class="custkey">CellFormat</span>(<span class="key">new</span> <span class="custkey">Alignment</span>() { WrapText = <span class="key">true</span>, Vertical = <span class="custkey">VerticalAlignmentValues</span>.Top }),

			<span class="com">// default2 - Cell StyleIndex = 1</span>
			<span class="key">new</span> <span class="custkey">CellFormat</span>(<span class="key">new</span> <span class="custkey">Alignment</span>() { WrapText = <span class="key">true</span>, Vertical = <span class="custkey">VerticalAlignmentValues</span>.Top }) { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = <span class="key">true</span> },

			<span class="com">// header - Cell StyleIndex = 2</span>
			<span class="key">new</span> <span class="custkey">CellFormat</span>(<span class="key">new</span> <span class="custkey">Alignment</span>() { WrapText = <span class="key">true</span>, Vertical = <span class="custkey">VerticalAlignmentValues</span>.Top }) { FontId = 1, FillId = 0, BorderId = 1, ApplyFill = <span class="key">true</span> },

			<span class="com">// DateTime DataType - Cell StyleIndex = 3</span>
			<span class="key">new</span> <span class="custkey">CellFormat</span>(<span class="key">new</span> <span class="custkey">Alignment</span>() { Vertical = <span class="custkey">VerticalAlignmentValues</span>.Top }) { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = <span class="key">true</span>, NumberFormatId = 15, ApplyNumberFormat = <span class="key">true</span> },

			<span class="com">// int,long,short DataType - Cell StyleIndex = 4</span>
			<span class="key">new</span> <span class="custkey">CellFormat</span>(<span class="key">new</span> <span class="custkey">Alignment</span>() { WrapText = <span class="key">true</span>, Vertical = <span class="custkey">VerticalAlignmentValues</span>.Top }) { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = <span class="key">true</span>, NumberFormatId = 1 },

			<span class="com">// decimal DataType  - Cell StyleIndex = 5</span>
			<span class="key">new</span> <span class="custkey">CellFormat</span>(<span class="key">new</span> <span class="custkey">Alignment</span>() { WrapText = <span class="key">true</span>, Vertical = <span class="custkey">VerticalAlignmentValues</span>.Top }) { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = <span class="key">true</span>, NumberFormatId = 2 }
			);
		<span class="key">return</span> cellFormats;
	}

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">Borders</span> GenerateBorders()
	{
		<span class="custkey">Borders</span> borders = <span class="key">new</span> <span class="custkey">Borders</span>(
			<span class="com">// index 0 default</span>
			<span class="key">new</span> <span class="custkey">Border</span>(),

			<span class="com">// index 1 black border</span>
			<span class="key">new</span> <span class="custkey">Border</span>( 
				<span class="key">new</span> <span class="custkey">LeftBorder</span>(<span class="key">new</span> <span class="custkey">Color</span>() { Auto = <span class="key">true</span> }) { Style = <span class="custkey">BorderStyleValues</span>.Thin },
				<span class="key">new</span> <span class="custkey">RightBorder</span>(<span class="key">new</span> <span class="custkey">Color</span>() { Auto = <span class="key">true</span> }) { Style = <span class="custkey">BorderStyleValues</span>.Thin },
				<span class="key">new</span> <span class="custkey">TopBorder</span>(<span class="key">new</span> <span class="custkey">Color</span>() { Auto = <span class="key">true</span> }) { Style = <span class="custkey">BorderStyleValues</span>.Thin },
				<span class="key">new</span> <span class="custkey">BottomBorder</span>(<span class="key">new</span> <span class="custkey">Color</span>() { Auto = <span class="key">true</span> }) { Style = <span class="custkey">BorderStyleValues</span>.Thin },
				<span class="key">new</span> <span class="custkey">DiagonalBorder</span>())
			);
		<span class="key">return</span> borders;
	}

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">Fills</span> GenerateFills()
	{
		<span class="custkey">Fills</span> fills = <span class="key">new</span> <span class="custkey">Fills</span>(
			<span class="com">// Index 0</span>
			<span class="key">new</span> <span class="custkey">Fill</span>(<span class="key">new</span> <span class="custkey">PatternFill</span>() { PatternType = <span class="custkey">PatternValues</span>.None }),

			<span class="com">// Index 1</span>
			<span class="key">new</span> <span class="custkey">Fill</span>(<span class="key">new</span> <span class="custkey">PatternFill</span>() { PatternType = <span class="custkey">PatternValues</span>.Gray125 }),

			<span class="com">// Index 2 - header</span>
			<span class="key">new</span> <span class="custkey">Fill</span>(<span class="key">new</span> <span class="custkey">PatternFill</span>(<span class="key">new</span> <span class="custkey">ForegroundColor</span> { Rgb = <span class="key">new</span> <span class="custkey">HexBinaryValue</span>() { Value = <span class="str">"66666666"</span> } }) { PatternType = <span class="custkey">PatternValues</span>.Solid })  
			);
		<span class="key">return</span> fills;
	}

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">Fonts</span> GenerateFonts()
	{
		<span class="custkey">Fonts</span> fonts = <span class="key">new</span> <span class="custkey">Fonts</span>(
			<span class="com">// Index 0 - default</span>
			<span class="key">new</span> <span class="custkey">Font</span>( 
				<span class="key">new</span> <span class="custkey">FontSize</span>() { Val = 10 },
				<span class="key">new</span> <span class="custkey">FontName</span>() { Val = <span class="str">"Arial Unicode"</span> }
			),

			<span class="com">// Index 1 - header</span>
			<span class="key">new</span> <span class="custkey">Font</span>( 
				<span class="key">new</span> <span class="custkey">FontSize</span>() { Val = 10 },
				<span class="key">new</span> <span class="custkey">Bold</span>()<span class="com">//,</span>

			<span class="com">//new Color() { Rgb = "FFFFFF" }</span>

			));
		<span class="key">return</span> fonts;
	}

	<span class="key">private</span> <span class="key">static</span> <span class="custkey">Cell</span> GetCellWithDataType(<span class="key">string</span> cellRef, <span class="key">object</span> value, <span class="custkey">Type</span> type)
	{
		<span class="key">if</span> (type == <span class="key">typeof</span>(<span class="custkey">DateTime</span>))
		{
			<span class="custkey">Cell</span> cell = <span class="key">new</span> <span class="custkey">Cell</span>()
			{
				DataType = <span class="key">new</span> <span class="custkey">EnumValue</span>&lt;<span class="custkey">CellValues</span>&gt;(<span class="custkey">CellValues</span>.Number),
				StyleIndex = 3
			};

			<span class="key">if</span> (value != <span class="custkey">DBNull</span>.Value)
			{
				System.Globalization.<span class="custkey">CultureInfo</span> cultureinfo = <span class="key">new</span> System.Globalization.<span class="custkey">CultureInfo</span>(<span class="str">"en-US"</span>);
				<span class="custkey">DateTime</span> valueDate = (<span class="custkey">DateTime</span>)value;
				<span class="key">string</span> valueString = valueDate.ToOADate().ToString(cultureinfo);
				<span class="custkey">CellValue</span> cellValue = <span class="key">new</span> <span class="custkey">CellValue</span>(valueString);
				cell.Append(cellValue);
			}

			<span class="key">return</span> cell;
		}
		<span class="key">if</span> (type == <span class="key">typeof</span>(<span class="key">long</span>) || type == <span class="key">typeof</span>(<span class="key">int</span>) || type == <span class="key">typeof</span>(<span class="key">short</span>))
		{
			<span class="custkey">Cell</span> cell = <span class="key">new</span> <span class="custkey">Cell</span>() { CellReference = cellRef, CellValue = <span class="key">new</span> <span class="custkey">CellValue</span>(value.ToString()), DataType = <span class="custkey">CellValues</span>.Number };
			cell.StyleIndex = 4;
			<span class="key">return</span> cell;
		}
		<span class="key">if</span> (type == <span class="key">typeof</span>(<span class="key">decimal</span>))
		{
			<span class="custkey">Cell</span> cell = <span class="key">new</span> <span class="custkey">Cell</span>() { CellReference = cellRef, CellValue = <span class="key">new</span> <span class="custkey">CellValue</span>(value.ToString()), DataType = <span class="custkey">CellValues</span>.Number };
			cell.StyleIndex = 5;
			<span class="key">return</span> cell;
		}
		<span class="key">else</span>
		{
			<span class="custkey">Cell</span> cell = <span class="key">new</span> <span class="custkey">Cell</span>() { CellReference = cellRef, CellValue = <span class="key">new</span> <span class="custkey">CellValue</span>(value.ToString()), DataType = <span class="custkey">CellValues</span>.String };
			cell.StyleIndex = 1;
			<span class="key">return</span> cell;
		}
	}
} </code></pre>



<br><br>



<p id="SwaggerOutput">Run the application and <strong>test export to excel functionality from Swagger</strong>.</p>



<h5 class="wp-block-heading"><em><span style="text-decoration: underline;">Execute the Get Excel API</span></em></h5>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="529" height="282" src="https://www.codeindotnet.com/wp-content/uploads/2022/08/call-get-export-to-excel-api-csharp.png" alt="" class="wp-image-1930" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/08/call-get-export-to-excel-api-csharp.png 529w, https://www.codeindotnet.com/wp-content/uploads/2022/08/call-get-export-to-excel-api-csharp-300x160.png 300w" sizes="auto, (max-width: 529px) 100vw, 529px" /></figure>



<br><br>



<p>The below screenshot shows a successful API response code-200 with downloadable Excel file &#8211;<strong>SampleExcel.xls</strong></p>



<p><span style="text-decoration: underline;"><em>Output</em></span></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="741" height="380" src="https://www.codeindotnet.com/wp-content/uploads/2022/08/download-export-to-excel-file-web-api-csharp.png" alt="" class="wp-image-1931" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/08/download-export-to-excel-file-web-api-csharp.png 741w, https://www.codeindotnet.com/wp-content/uploads/2022/08/download-export-to-excel-file-web-api-csharp-300x154.png 300w" sizes="auto, (max-width: 741px) 100vw, 741px" /></figure>



<p>You might receive a &#8216;trust source&#8217; warning popup message while opening the downloaded file. Just click on the &#8216;Yes&#8217; button to open the excel file.</p>



<br>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="595" height="355" src="https://www.codeindotnet.com/wp-content/uploads/2022/08/customized-excel-sheet-output-with-different-cell-formats-styles.png" alt="" class="wp-image-2049" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/08/customized-excel-sheet-output-with-different-cell-formats-styles.png 595w, https://www.codeindotnet.com/wp-content/uploads/2022/08/customized-excel-sheet-output-with-different-cell-formats-styles-300x179.png 300w" sizes="auto, (max-width: 595px) 100vw, 595px" /></figure>



<br>



<p>That&#8217;s all about generating the multi-sheet excel file from DataSet.</p>



<br><br>



<p>Now, we will see <strong>how to format Header or Body Cell</strong> like wrapping text, changing fonts, filling colors to a cell, resizing the column width, and applying borders from code.</p>



<h2 class="wp-block-heading" id="StyleIndex"><strong>How to work with style Index in Open XML?</strong></h2>



<p>To apply different styles to a cell, create a set of Cell formats or &#8216;StyleIndex&#8217; and assign that particular format while creating a Cell. For example, if you want to fill color for a Header Cell then you need to define two indexes or formats &#8211; </p>



<ol class="wp-block-list">
<li>Style Index 0 &#8211; &#8216;no fill&#8217; as default (white color) which applies to common body Cell</li>



<li>Style Index 1 &#8211; fill with light grey color for Header Cell</li>
</ol>



<p>While creating a Header apply &#8216;Index 1&#8217; to the cell property and for normal Cells use &#8216;Index 0&#8217;. <br>So in this way, all Cell styles or formats are defined in this sample code. The below screenshots shows the code flow of Cell StyleIndex.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="634" height="473" src="https://www.codeindotnet.com/wp-content/uploads/2022/08/cell-style-index-in-open-xml.png" alt="" class="wp-image-2006" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/08/cell-style-index-in-open-xml.png 634w, https://www.codeindotnet.com/wp-content/uploads/2022/08/cell-style-index-in-open-xml-300x224.png 300w" sizes="auto, (max-width: 634px) 100vw, 634px" /></figure>



<br>



<h2 class="wp-block-heading"><strong><span style="text-decoration: underline;">Cell StyleIndex Code Flow &#8211; Explanation</span></strong></h2>



<br>



<h3 class="wp-block-heading"><strong>1. Create Cell Formats &#8211; StyleIndex</strong></h3>



<p>First, create different Cell formats. We have created six cell formats, refer  <strong>GenerateCellFormats()</strong> method in the example above:</p>



<ol class="wp-block-list">
<li>StyleIndex = 0 &#8211; Default without border</li>



<li>StyleIndex = 1 &#8211; Default with border</li>



<li>StyleIndex = 2 &#8211; for Header cell</li>



<li>StyleIndex = 3 &#8211; DateTime data type cell </li>



<li>StyleIndex = 4 &#8211; Integer data type cell</li>



<li>StyleIndex = 5 &#8211; decimal data type cell</li>
</ol>



<p>Apply the correct style index when creating a cell. Please find the following lines in the code: <br><strong>a) CellFormats GenerateCellFormats()</strong> &#8211; Method<br>// header &#8211; Cell StyleIndex = 2<br>new CellFormat(new Alignment() { WrapText = true, Vertical = VerticalAlignmentValues.Top }) { <mark style="background-color:#f2f19d" class="has-inline-color">FontId</mark> = 1, <mark style="background-color:#f2f19d" class="has-inline-color">FillId</mark> = 0, <mark style="background-color:#f2f19d" class="has-inline-color">BorderId</mark> = 1, ApplyFill = true }, <br><strong>b) apply style index to the header cell</strong> <br>cellHeader.<mark style="background-color:#f2f19d" class="has-inline-color">StyleIndex </mark>= 2;</p>



<br>



<h3 class="wp-block-heading"><strong>2. Create Indexes for Font, Border, Fill</strong></h3>



<p>FontId, FillId and BorderId are defined with some index value, in each CellFormats. So, you have to define a set of styles for each attribute. </p>



<h4 class="wp-block-heading"><strong>i.</strong> Defining Font Index</h4>



<p>Refer <strong>GenerateFonts()</strong> method in code &#8211; defines two indexes: one for the normal cell (default) and another for the header cell. See the highlighted text above &#8211; <mark style="background-color:#f2f19d" class="has-inline-color">FontId</mark> = 1</p>



<h4 class="wp-block-heading"><strong>ii.</strong> Define Borders</h4>



<p>Refer <strong>GenerateBorders()</strong> method in code &#8211; defines two indexes: one without borderline and another with borderline. See the highlighted text above &#8211; <mark style="background-color:#f2f19d" class="has-inline-color">BorderId</mark> = 1, </p>



<h4 class="wp-block-heading"><strong>iii.</strong> Define Fill Colors</h4>



<p>Refer <strong>GenerateFills()</strong> method in code &#8211; defines three indexes. <br>See the highlighted text above &#8211; FillId = 0. It applies the default color to a cell.</p>



<br>



<h3 class="wp-block-heading"><strong>How to Customize Column Width &#8211; OpenXml</strong></h3>



<p>Refer <strong>SetDefaultColumnWidth()</strong> method in code &#8211; defines width size up to 400 columns. &#8216;Min&#8217; &amp; &#8216;Max&#8217; is a column range. As shown in the screenshot below, the first column&#8217;s Min &amp; Max value is 1 which means the width size 25 is applicable only to the 1<sup>st</sup> column. <br>In the same way, width size 50 is for the 2<sup>nd</sup> column. <br>If you want to assign the same width value to more than one column then increase the Max property value. Width column size 10 is applied from the 3<sup>rd</sup> to 400<sup>th</sup> columns in the code.</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="568" height="186" src="https://www.codeindotnet.com/wp-content/uploads/2022/08/customize-column-width-open-xml.png" alt="" class="wp-image-2043" srcset="https://www.codeindotnet.com/wp-content/uploads/2022/08/customize-column-width-open-xml.png 568w, https://www.codeindotnet.com/wp-content/uploads/2022/08/customize-column-width-open-xml-300x98.png 300w" sizes="auto, (max-width: 568px) 100vw, 568px" /></figure>



<p><br><br>Hope you liked it! Happy Coding!! Thanks&nbsp;<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br></p>



<p><br></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/export-dataset-to-excel-in-c-net-core-openxml/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
