<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Evolving Engineer]]></title><description><![CDATA[This blog shares my software development knowledge from both professional and personal experiences. It explores C#, .NET, clean coding, distributed systems, event-driven architecture, TDD etc.]]></description><link>https://evolving-engineer.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1727240906670/18e36322-905d-46de-8423-633f26f2a3ab.png</url><title>Evolving Engineer</title><link>https://evolving-engineer.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 24 Nov 2026 10:20:28 GMT</lastBuildDate><atom:link href="https://evolving-engineer.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[SOLID Principles: Applying Single Responsibility Principle to Real-World Code]]></title><description><![CDATA[Learn to apply Single Responsibility Principle (SRP) with a practical example by refactoring Orchestrator class]]></description><link>https://evolving-engineer.hashnode.dev/single-responsibility-principle-practical-example</link><guid isPermaLink="true">https://evolving-engineer.hashnode.dev/single-responsibility-principle-practical-example</guid><category><![CDATA[C#]]></category><category><![CDATA[.NET]]></category><category><![CDATA[single responsibility principle]]></category><category><![CDATA[SRP]]></category><category><![CDATA[best practices]]></category><category><![CDATA[SOLID principles]]></category><category><![CDATA[solid]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[dotnetcore]]></category><category><![CDATA[asp.net core]]></category><category><![CDATA[ASP.NET]]></category><dc:creator><![CDATA[Vedant Phougat]]></dc:creator><pubDate>Mon, 30 Sep 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727238409948/55b71672-8caf-418c-b7a0-b3b366c710dd.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-introduction">1. Introduction</h1>
<p>Ever wondered why you found yourself modifying the same class to accommodate unrelated features? Imagine having a class responsible for processing invoices, but over time, it has become the go to class to fix issues related to database queries, business rules, and external API calls. This is a common issue when classes take on multiple responsibilities, leading to code that's difficult to maintain and extend.</p>
<p>This post will provide you with practical insights into identifying, breaking down and refactoring a class – <code>InvoiceMatchOrchestrator</code>, that is performing multiple tasks, by applying <strong>Single Responsibility Principle</strong> (<strong>SRP</strong> from here) to a real-world example. First, let's start with the formal definition:</p>
<blockquote>
<p><em>A class should have only one reason to change</em>.</p>
</blockquote>
<p>Now let's start by looking at the project requirements that led to our initial approach.</p>
<p><strong>NOTE:</strong> For brevity I have omitted additional code such as</p>
<ul>
<li><p>initializing <code>HttpClient</code> and <code>OpenSearchClient</code></p>
</li>
<li><p>further refactoring of specialized classes (which may or may not be violating SRP).</p>
</li>
</ul>
<h1 id="heading-2-requirements">2. Requirements</h1>
<p>A developer is tasked with developing a service to match invoices from two distinct sources, <strong>PA</strong> and <strong>IA</strong>, based on specific business logic. This involves fetching invoices from both sources, comparing them according to the matching criteria, and saving the matched invoices back to <strong>PA</strong>. The goal is to streamline this workflow while keeping the code readable, maintainable and adaptable for future changes.</p>
<h3 id="heading-21-expected-workflow-logic">2.1. Expected workflow logic</h3>
<p>A class named <code>InvoiceMatchOrchestrator</code> is responsible for managing the invoice matching workflow logic. <strong>What is invoice matching workflow logic?</strong></p>
<blockquote>
<p><em>It is the order of steps – fetching invoices from both data sources, applying business logic to find matches, and saving matched invoices back to</em> <strong><em>PA</em></strong>*.*</p>
</blockquote>
<h3 id="heading-22-technical-details">2.2. Technical details</h3>
<ul>
<li><p><strong>PA's data source:</strong> <code>PostgreSQL</code>, accessed via a <a target="_blank" href="https://hasura.io/docs/2.0/getting-started/how-it-works/index/">Hasura GraphQL</a> layer, which provides a GraphQL API for database interaction.</p>
</li>
<li><p><strong>IA's data source:</strong> <code>OpenSearch</code>, used as an external reference source for comparison</p>
</li>
<li><p><strong>Programming language:</strong> <code>C#</code>.</p>
</li>
</ul>
<h1 id="heading-3-development">3. Development</h1>
<p>Although the developer is proficient in <code>C#</code> and <code>.NET</code>, he is using some of the project's other technologies for the first time. With a tight deadline for an upcoming demo, he needs to develop the application quickly despite his unfamiliarity with these technologies.</p>
<h3 id="heading-31-initial-approach">3.1. Initial approach</h3>
<p>Since the developer is facing a tight deadline, he opts for a quick, all-in-one approach to get the application ready for the demo. This initial approach involves creating a single class called <code>InvoiceMatchOrchestrator</code> that handles the following tasks on its own:</p>
<ul>
<li><p><strong>Fetching invoices from PA:</strong> Creates and configures an <code>HttpClient</code> instance to connect to <strong>PA</strong>'s data source.</p>
</li>
<li><p><strong>Fetching invoices from IA:</strong> Creates and configures an <code>OpenSearchClient</code> instance to connect to <strong>IA</strong>’s data source.</p>
</li>
<li><p><strong>Matching invoices:</strong> Implements business logic to match the invoices from <strong>PA</strong> and <strong>IA</strong>.</p>
</li>
<li><p><strong>Saving matched invoices:</strong> Saves the matched invoices back to <strong>PA</strong> using <code>HttpClient</code>.</p>
</li>
</ul>
<h3 id="heading-32-initial-orchestrator-code">3.2. Initial Orchestrator code</h3>
<p>After the initial developement phase, the code for <code>InvoiceMatchOrchestrator</code> looks as follows:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">InvoiceMatchOrchestrator</span>
{
    <span class="hljs-comment">// This method's job is to orchestrate the invoice matching process</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> ICollection&lt;Int32&gt; <span class="hljs-title">ExecuteMatching</span>(<span class="hljs-params">Int32 batchId</span>)</span>
    {
        <span class="hljs-comment">// ------ Fetch invoices from PA ------</span>
        <span class="hljs-keyword">var</span> query_FetchInvoices = <span class="hljs-string">"it contains hasura query to fetch invoices"</span>;
        <span class="hljs-keyword">var</span> httpClient = <span class="hljs-keyword">new</span> HttpClient();
        <span class="hljs-comment">// configure httpClient and create the message request using batchId</span>
        <span class="hljs-keyword">var</span> response = httpClient.SendAsync(request);
        <span class="hljs-comment">// check and parse the response</span>
        <span class="hljs-keyword">var</span> paInvoices = JsonSerializer.Deserialize&lt;List&lt;PaInvoice&gt;&gt;(stringifyJson);

        <span class="hljs-comment">// ------ Fetch invoices from IA ------</span>
        <span class="hljs-keyword">var</span> openSearchClient = <span class="hljs-keyword">new</span> OpenSearchClient();
        <span class="hljs-comment">// configure the openSearchClient and create search request using batchId</span>
        <span class="hljs-keyword">var</span> iaInvoices = openSearchClient.Search&lt;List&lt;IaInvoice&gt;&gt;(searchRequest);

        <span class="hljs-comment">// ------ Find matching invoices ------</span>
        <span class="hljs-comment">// logic to find the matching invoices</span>

        <span class="hljs-comment">// ------ Save matching invoices ------</span>
        <span class="hljs-keyword">var</span> mutation_SaveMatches = <span class="hljs-string">"it contains hasura query to save invoices"</span>;
        <span class="hljs-comment">// create the save request using matched invoices</span>
        <span class="hljs-keyword">var</span> saveResponse = httpClient.SendAsync(saveRequest);
        <span class="hljs-comment">// check and parse the response to generate the IDs of the saved result</span>
        <span class="hljs-keyword">return</span> ids;
    }
}
</code></pre>
<h3 id="heading-33-challenges-with-initial-orchestrator">3.3. Challenges with initial Orchestrator</h3>
<p>As development progressed, this initial approach quickly became complex and hard to adapt. With each new requirement, such as:</p>
<ul>
<li><p>Saving matched invoices to <strong>IA</strong> (<code>OpenSearch</code>) in addition to <strong>PA</strong>.</p>
</li>
<li><p>Adjusting the invoice matching criteria to use a different field, <code>x</code> (abstracted for confidentiality) instead of <code>y</code>.</p>
</li>
</ul>
<p>the <code>InvoiceMatchOrchestrator</code> class required significant code changes, making it increasingly error prone. This <strong>Initial Approach</strong> bundled multiple responsibilities within one class causing any new requirement to impact unrelated parts of the code, thus introducing risks and reducing reliability.</p>
<h1 id="heading-4-refactor">4. Refactor</h1>
<p>After the demo, the developer should pause to evaluate how new requirements might impact the <code>InvoiceMatchOrchestrator</code> class. While the initial approach was suitable for meeting the deadline, it's now important to consider whether this design will continue to support future changes efficiently. And if he finds potential issues, like increased complexity or the need for frequent modifications, refactoring is necessary.</p>
<p>It is also part of the developer's role to communicate and explain this to stakeholders, highlighting why <em>time for refactoring</em> is needed, the long-term benefits it offers, and how it will make future changes quicker and easier.</p>
<h3 id="heading-41-identifying-separate-responsibilities">4.1. Identifying separate responsibilities</h3>
<p>With the challenges identified in the <strong>Development</strong> section, we’ll now focus on refactoring the <code>InvoiceMatchOrchestrator</code> class by applying the <strong>SRP</strong>. The goal is to make this class perform task that aligns with its name and delegate everything else to specialized classes by clearly separating responsibilities. To determine if a class is handling multiple responsibilities, ask these questions:</p>
<ul>
<li><p><strong>What is the primary purpose of the class?</strong> In the case of <code>InvoiceMatchOrchestrator</code>, its main job is to manage workflow logic related to invoice matching.</p>
</li>
<li><p><strong>Should this class change when requirements unrelated to the workflow logic are introduced?</strong> If the answer is "yes", the class likely has multiple responsibilities or named incorrectly. For <code>InvoiceMatchOrchestrator</code>, any change to data-fetching or saving steps would require updates, even though these tasks aren't part of its main workflow management role.</p>
</li>
</ul>
<p>Using the above-mentioned questions, let’s consider when the <code>InvoiceMatchOrchestrator</code> class should be modified if the following new requirements arise:</p>
<ol>
<li><p>How invoices should be fetched from <strong>PA</strong>? No ❌</p>
</li>
<li><p>How invoices should be fetched from <strong>IA</strong>? No ❌</p>
</li>
<li><p>How invoices should be matched? No ❌</p>
</li>
<li><p>How matched invoices should be saved to <strong>PA</strong>? No ❌</p>
</li>
</ol>
<p>These answers confirm that <code>InvoiceMatchOrchestrator</code> should delegate each of these tasks to specialized classes to ensure it adheres to SRP by focusing only on coordinating the invoice matching workflow.</p>
<h3 id="heading-42-applying-srp">4.2. Applying SRP</h3>
<p>With the separate responsibilities identified, we'll apply SRP by delegating each task to its respective class:</p>
<ul>
<li>Create <code>HasuraClient</code> to handle communication between the application and Hasura server.</li>
</ul>
<pre><code class="lang-csharp">  <span class="hljs-comment">//-------- Hasura Client --------</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IHasuraClient</span>
  {
      <span class="hljs-function">Task&lt;HasuraResponse&gt; <span class="hljs-title">SendAsync</span>(<span class="hljs-params">HasuraRequest request</span>)</span>;
  }

  <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">HasuraClient</span> : <span class="hljs-title">IHasuraClient</span>
  {
      <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> HttpClient _client;

      <span class="hljs-comment">//See: https://learn.microsoft.com/en-us/dotnet/core/extensions/httpclient-factory#typed-clients</span>
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">HasuraClient</span>(<span class="hljs-params">HttpClient client</span>)</span>
      {
          _client = client;
      }

      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;HasuraResponse&gt; <span class="hljs-title">SendAsync</span>(<span class="hljs-params">HasuraRequest request</span>)</span>
      {
          <span class="hljs-comment">//create HttpRequestMessage object from HasuraRequest</span>
          <span class="hljs-keyword">var</span> responseMessage = <span class="hljs-keyword">await</span> _client.SendAsync(requestMessage)
          <span class="hljs-comment">//check and parse to HasuraResponse and return</span>
          <span class="hljs-keyword">return</span> response;
      }
  }
</code></pre>
<ul>
<li>Create a <code>PaInvoiceService</code> to deal with invoices from PA using an injected <code>HasuraClient</code>.</li>
</ul>
<pre><code class="lang-csharp">  <span class="hljs-comment">//-------- Pa Invoice Service --------</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IPaInvoiceService</span>
  {
      Task&lt;ICollection&lt;PaInvoice&gt;&gt; GetInvoicesForBatchAsync(Int32 batchId);
  }

  <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">PaInvoiceService</span> : <span class="hljs-title">IPaInvoiceService</span>
  {
      <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> String GetInvoicesForBatchQuery = <span class="hljs-string">"hasura query"</span>;
      <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IHasuraClient _client;

      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PaInvoiceService</span>(<span class="hljs-params">IHasuraClient client</span>)</span>
      {
          _client = client;
      }

      <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;ICollection&lt;PaInvoice&gt;&gt; GetInvoicesForBatchAsync(Int32 batchId)
      {
          <span class="hljs-comment">//create HasuraRequest object using GetInvoicesForBatchQuery+batchId</span>
          <span class="hljs-keyword">var</span> hasuraResponse = <span class="hljs-keyword">await</span> _client.SendAsync(hasuraRequest);
          <span class="hljs-comment">//validate and return invoices</span>
          <span class="hljs-keyword">return</span> hasuraResponse.Value;
      }
  }
</code></pre>
<ul>
<li>Create an <code>IaInvoiceService</code> to deal with invoices from IA using an injected <code>OpenSearchClient</code></li>
</ul>
<pre><code class="lang-csharp">  <span class="hljs-comment">//-------- Ia Invoice Service --------</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IIaInvoiceService</span>
  {
      Task&lt;ICollection&lt;IaInvoice&gt;&gt; GetInvoicesForBatchAsync(Int32 batchId);
  }

  <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">IaInvoiceService</span> : <span class="hljs-title">IIaInvoiceService</span>
  {
      <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> OpenSearchClient _client;

      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">IaInvoiceService</span>(<span class="hljs-params">OpenSearchClient client</span>)</span>
      {
          _client = client;
      }

      <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;ICollection&lt;IaInvoice&gt;&gt; GetInvoicesForBatchAsync(Int32 batchId)
      {
          <span class="hljs-comment">//create an object of OpenSearchRequest using batchId</span>
          <span class="hljs-keyword">var</span> openSearchResponse = <span class="hljs-keyword">await</span> _client.SearchAsync(openSearchRequest);
          <span class="hljs-comment">//check response, extract the invoices fetched, and return</span>
          <span class="hljs-keyword">return</span> openSearchResponse.Value;
      }
  }
</code></pre>
<ul>
<li>Develop an <code>InvoiceMatchProcessor</code> class responsible for the invoice matching logic. This allows the matching rules to be isolated, making it easy to modify as the business logic evolves.</li>
</ul>
<pre><code class="lang-csharp">  <span class="hljs-comment">//-------- Invoice Match Processor --------</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IMatchProcessor</span>
  {
      <span class="hljs-function">ICollection&lt;Match&gt; <span class="hljs-title">MatchInvoices</span>(<span class="hljs-params">
          ICollection&lt;PaInvoice&gt; paInvoices,
          ICollection&lt;IaInvoice&gt; iaInvoices</span>)</span>;
  }

  <span class="hljs-comment">//------ Implementation ------</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">InvoiceMatchProcessor</span> : <span class="hljs-title">IMatchProcessor</span>
  {
      <span class="hljs-function"><span class="hljs-keyword">public</span> ICollection&lt;Invoice&gt; <span class="hljs-title">MatchInvoices</span>(<span class="hljs-params">
          ICollection&lt;PaInvoice&gt; paInvoices,
          ICollection&lt;IaInvoice&gt; iaInvoices</span>)</span>
      {
          <span class="hljs-comment">//the logic to match the invoices</span>
          <span class="hljs-keyword">return</span> matchedInvoices;
      }
  }
</code></pre>
<ul>
<li>Introduce an <code>InvoiceService</code> to handle saving the matched invoices to <strong>PA</strong>. This class will encapsulate the saving logic such as saving to additional data sources or adjusting to changing persistence requirements.</li>
</ul>
<pre><code class="lang-csharp">  <span class="hljs-comment">//-------- Matched Invoice Service --------</span>
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IInvoiceService</span>
  {
      Task&lt;ICollection&lt;Int32&gt;&gt; SaveMatchesAsync(ICollection&lt;Invoice&gt; matches);
  }

  <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">InvoiceService</span> : <span class="hljs-title">IInvoiceService</span>
  {
      <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> String SaveMatchedInvoiceMutation = <span class="hljs-string">"hasura-mutation"</span>;
      <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IHasuraClient _client;

      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">InvoiceService</span>(<span class="hljs-params">HasuraClient client</span>)</span>
      {
          _client = client;
      }

      <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;ICollection&lt;Int32&gt;&gt; SaveMatchesAsync(ICollection&lt;Invoice&gt; matches)
      {
          <span class="hljs-comment">//Use SaveMatchMutation + matches to create an object of HasuraRequest</span>
          <span class="hljs-keyword">var</span> response = _client.SendAsync(request);
          <span class="hljs-comment">//extract collection of Ids of newly created matches from HasuraResponse</span>
          <span class="hljs-keyword">return</span> response.Value;
      }
  }
</code></pre>
<p>By isolating each responsibility in a dedicated class, we ensure that changes to one responsibility will only impact the relevant class, not the orchestrator or unrelated functionality.</p>
<h3 id="heading-43-refactored-orchestrator">4.3. Refactored Orchestrator</h3>
<p>After refactoring, the <code>InvoiceMatchOrchestrator</code> class now looks like this:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">InvoiceMatchOrchestrator</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IPaInvoiceService _paInvoiceService;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IIaInvoiceService _iaInvoiceService;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMatchProcessor _invoiceMatchProcessor;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IInvoiceService _invoiceService;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">InvoiceMatchOrchestrator</span>(<span class="hljs-params">
        IPaInvoiceService paInvoiceService,
        IIaInvoiceService iaInvoiceService,
        IMatchProcessor invoiceMatchProcessor,
        IInvoiceService invoiceService</span>)</span>
    {
        _paInvoiceService = paInvoiceService;
        _iaInvoiceService = iaInvoiceService;
        _invoiceMatchProcessor = invoiceMatchProcessor;
        _invoiceService = invoiceService;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;ICollection&lt;<span class="hljs-keyword">int</span>&gt;&gt; ExecuteMatching(<span class="hljs-keyword">int</span> batchId)
    {
        <span class="hljs-comment">// 1. Fetch invoices from PA</span>
        <span class="hljs-keyword">var</span> paInvoices = <span class="hljs-keyword">await</span> _paInvoiceService.GetInvoicesForBatchAsync(batchId);

        <span class="hljs-comment">// 2. Fetch invoices from IA</span>
        <span class="hljs-keyword">var</span> iaInvoices = <span class="hljs-keyword">await</span> _iaInvoiceService.GetInvoicesForBatchAsync(batchId);

        <span class="hljs-comment">// 3. Perform invoice matching</span>
        <span class="hljs-keyword">var</span> matchedInvoices = _invoiceMatchProcessor.MatchInvoices(paInvoices, iaInvoices);

        <span class="hljs-comment">// 4. Save the matched invoices</span>
        <span class="hljs-keyword">var</span> matchedInvoiceIds = <span class="hljs-keyword">await</span> _invoiceService.SaveMatchesAsync(matchedInvoices);
        <span class="hljs-keyword">return</span> matchedInvoiceIds;
    }
}
</code></pre>
<h1 id="heading-5-exercise">5. Exercise</h1>
<p>Let's say a new requirement is introduced and as per it – the matched invoices must also be saved in <strong>IA</strong> (<code>OpenSearch</code>) as well. The way this change can be incorporated:</p>
<ul>
<li><p><strong>Before refactoring –</strong> The <code>InvoiceMatchOrchestrator</code> class will be modified, which will lead to more complexity, making the code harder to maintain, test, and understand.</p>
</li>
<li><p><strong>After refactoring –</strong> First, these matched invoices are a collection of type <code>Invoice</code> and <code>InvoiceService</code> is responsible for handling <code>Invoice</code> operations. So, to implement new requirement, we will first create a dedicated client/service – let's call it <code>MyApplicationNameOpenSearchClient</code> – responsible for actually saving data to <code>OpenSearch</code>. This client will then be injected into the <code>InvoiceService</code>, where the <code>SaveMatchAsync</code> method will call both <code>HasuraClient</code> and <code>MyApplicationNameOpenSearchClient</code> to save the matched invoices. Thus leaving the <code>InvoiceMatchOrchestrator</code> untouched.</p>
</li>
</ul>
<p>The key point here is that only the class related to saving the matched invoices is modified and ensuring that the changes are isolated to their specific classes while the overall workflow remains unchanged.</p>
<h1 id="heading-6-conclusion">6. Conclusion</h1>
<p>So, refactoring the orchestrator class by applying the <strong>SRP</strong> resulted in cleaner, readable, and testable design. By separating concerns – such as fetching invoices from <strong>PA</strong> and <strong>IA</strong>, performing the matching logic, and saving the matched invoices – each of these tasks are now handled by their respective classes. This approach allows the orchestrator to manage the workflow logic, while making future modifications easier and less risky.</p>
<p>Since refactoring by applying <strong>SRP</strong> is an ongoing process, other classes withing the application, like <code>PaInvoiceService</code>, <code>IaInvoiceService</code>, etc, will be refactored as necessary, depending upon the frequency of changes and needs of the application.</p>
<h1 id="heading-7-feedback">7. Feedback</h1>
<p>Thank you for reading this post! Please leave any feedback in the comments about what could make this post better or topics you’d like to see next. Your suggestions help improve future posts and bring more helpful content.</p>
]]></content:encoded></item><item><title><![CDATA[Store Your App Configurations with Environment Variables: A Quick Guide]]></title><description><![CDATA[Learn to store secrets in environment variables to keep sensitive data out of codebase. Understand prefixes, naming conventions, and accessing them in…]]></description><link>https://evolving-engineer.hashnode.dev/store-app-configurations-with-environment-variables</link><guid isPermaLink="true">https://evolving-engineer.hashnode.dev/store-app-configurations-with-environment-variables</guid><category><![CDATA[secret management]]></category><category><![CDATA[Environment variables]]></category><category><![CDATA[configuration]]></category><category><![CDATA[.NET Configuration]]></category><category><![CDATA[ASP.NET Core Configuration]]></category><category><![CDATA[coding standards]]></category><category><![CDATA[best practices]]></category><category><![CDATA[configuration management]]></category><category><![CDATA[secrets management]]></category><category><![CDATA[.NET]]></category><category><![CDATA[ASP.NET]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Vedant Phougat]]></dc:creator><pubDate>Tue, 24 Sep 2024 07:24:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727163105750/bd2561a6-7ba9-4bac-8a72-e744f439425e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p><mark>NOTE – Storing secrets in environment variables is not a security feature, in fact it is an approach to keep your secrets separate from your codebase.</mark> Browse the answers of this <a target="_blank" href="https://stackoverflow.com/questions/12461484/is-it-secure-to-store-passwords-as-environment-variables-rather-than-as-plain-t">Stackoverflow question</a> for details about security in environment variables.</p>
<p>This post is about storing application secrets and confidential configurations in environment variables. But why should we store secrets and other confidential settings this way? Because this approach keeps the sensitive information out of the codebase, which:</p>
<ul>
<li><p>Reduces the risk of accidentally exposing secrets through source code repositories or version control systems.</p>
</li>
<li><p>Allows us to deploy the same codebase across environments while specifying different settings for each environment.</p>
</li>
<li><p>Allows us to change settings on the fly without modifying the application code.</p>
</li>
</ul>
<h1 id="heading-why-prefix-the-variables">Why prefix the variables?</h1>
<ul>
<li><p>To <strong>avoid naming conflicts</strong>, for example, two applications might use a variable named: <code>ConnectionString</code>. By prefixing application name/key to the variable, ensures that a specific application’s variables are unique.</p>
</li>
<li><p>For <strong>ease of readability and maintenance</strong> by grouping all configuration keys related to a specific application together.</p>
</li>
<li><p>When using configuration builders like <code>.AddEnvironmentVariables("MyApp_")</code> in .NET, the use of prefix allows the application to load only the <code>MyApp</code> specific variables and <strong>avoids accidentally picking up of variables intended for other applications</strong>.</p>
</li>
</ul>
<pre><code class="lang-bash"><span class="hljs-comment">## Connection string for application named: WayneEnterprise </span>
WayneEnterprise_ConnectionString

<span class="hljs-comment">## Connection string for application named: Batman</span>
Batman_ConnectionString
</code></pre>
<h1 id="heading-mapping-environment-variables-with-configuration-classes">Mapping environment variables with configuration classes</h1>
<h3 id="heading-configuration-classes">Configuration classes</h3>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AwsConfiguration</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> String SectionKey = <span class="hljs-string">"AwsConfiguration"</span>;

    <span class="hljs-keyword">public</span> String AccessKey { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> String SecretKey { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> EndpointConfiguration Endpoint { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> List&lt;String&gt; Regions { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> Dictionary&lt;String, String&gt; DetailTypes { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EndpointConfiguration</span>
{
    <span class="hljs-keyword">public</span> String Url { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> Int32 Port { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<h3 id="heading-naming-convention-for-environment-variables">Naming convention for environment variables</h3>
<pre><code class="lang-csharp"><span class="hljs-meta">## Simple Properties</span>
MyAwsApp_AwsConfiguration__AccessKey
MyAwsApp_AwsConfiguration__SecretKey

<span class="hljs-meta">## Nested Properties</span>
MyAwsApp_AwsConfiguration__Enpoint__Url
MyAwsApp_AwsConfiguration__Enpoint__Port

<span class="hljs-meta">## Collection/Array Properties</span>
MyAwsApp_AwsConfiguration__Region__0
MyAwsApp_AwsConfiguration__Region__1
MyAwsApp_AwsConfiguration__Region__2

<span class="hljs-meta">## Dictionary Properties</span>
MyAwsApp_AwsConfiguration__DetailTypes__InProgress
MyAwsApp_AwsConfiguration__DetailTypes__Completed

<span class="hljs-meta">## These properties will not be picked by the `.AddEnvironmentVariables("MyAwsApp_")</span>
NOTMyAwsApp_AwsConfiguration__AccessKey
NOTMyAwsApp_AwsConfiguration__SecretKey
</code></pre>
<h3 id="heading-understanding-the-delimiters">Understanding the delimiters</h3>
<p>The single-underscore (_) is used with the main prefix only, while double-underscore (__) is used for complex properties.</p>
<p>Why not use <code>:</code> as the separator? Because as per MSDN:</p>
<blockquote>
<p>The <code>:</code> separator doesn’t work with environment variable hierarchical keys on all platforms. For example, the <code>:</code> separator is not supported by Bash. The double underscore, <code>__</code>, is:</p>
<ul>
<li><p>Supported by all platforms.</p>
</li>
<li><p>Automatically replaced by a colon, <code>:</code>.</p>
</li>
</ul>
</blockquote>
<h1 id="heading-accessing-environment-variables">Accessing environment variables</h1>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params">String[] args</span>)</span>
    {
        <span class="hljs-keyword">var</span> builder = <span class="hljs-keyword">new</span> ConfigurationBuilder()
            <span class="hljs-comment">//the prefix - "MyAwsApp_" will be removed from the environment variable names</span>
            .AddEnvironmentVariables(<span class="hljs-string">"MyAwsApp_"</span>);
        <span class="hljs-keyword">var</span> configuration = builder.Build();
        <span class="hljs-keyword">var</span> awsConfiguration = configuration
            .GetSection(AwsConfiguration.SectionKey)
            .Get&lt;AwsConfiguration&gt;();
    }
}
</code></pre>
<h1 id="heading-see-also">See also</h1>
<ul>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration">Configuration in .NET – MSDN</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-8.0">Configuration in ASP.NET – MSDN</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Using Result Filter and Exception Middleware (3/3)]]></title><description><![CDATA[Create a custom Result Filter to handle model-validation errors and Exception Middleware for exceptions]]></description><link>https://evolving-engineer.hashnode.dev/using-result-filter-and-exception-middleware-33</link><guid isPermaLink="true">https://evolving-engineer.hashnode.dev/using-result-filter-and-exception-middleware-33</guid><category><![CDATA[ASP.NET]]></category><category><![CDATA[Web API]]></category><category><![CDATA[Filter]]></category><category><![CDATA[Middleware]]></category><category><![CDATA[ProblemDetails]]></category><dc:creator><![CDATA[Vedant Phougat]]></dc:creator><pubDate>Sun, 09 Jul 2023 17:16:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688754008106/393e4bc3-373d-4a8b-bdc5-5503bdd74564.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-introduction">1. Introduction</h1>
<p>In this article, I will describe how one can use a custom result filter and exception middleware to handle model-validation errors and exceptions (custom as well as framework exceptions).</p>
<p>For the complete code, see the project: <a target="_blank" href="https://github.com/phougatv/web-api-fundamentals/tree/master/src/ErrorResponse/ViaFilterAndMiddleware">ViaFilterAndMiddleware</a> and for its test cases see the project: <a target="_blank" href="https://github.com/phougatv/web-api-fundamentals/tree/master/test/ErrorResponse/ViaFilterAndMiddlewareTest">ViaFilterAndMiddlewareTest</a></p>
<h1 id="heading-2-custom-result-filter-for-model-validation-errors">2. Custom result filter for model-validation errors</h1>
<p>We will first create a custom result filter for handling model-validation errors and then test it.</p>
<p><em>Why use a custom result filter for handling model-validation errors?</em> Because:</p>
<ul>
<li><p>In ASP.NET 6.0, upon model-validation errors, none of the methods; <code>OnActionExecuting</code> or <code>OnActionExecuted</code> of <code>IActionFilter</code> is invoked. Whereas, first <code>OnResultExecuting</code> and then <code>OnResultExecuted</code> method of <code>IResultFilter</code> is invoked.</p>
</li>
<li><p>It provides fine-grained control over the execution. So, one can choose to register it globally, <code>builder.Services.AddControllers(options =&gt; options.Filters.Add&lt;MyModelValidationResultFilter&gt;());</code>, which will invoke this filter on every call made to our application, or we can apply this as an attribute on specific <em>action methods</em> and <em>controllers</em> (doing this will enforce the filter on all action methods of that controllers).</p>
</li>
</ul>
<p><em>Our custom result filter is registered globally, why?</em> Because registering it globally will invoke it on every call, thus making sure if the model-validation failure has occurred or not. If it has then we can modify the response structure accordingly and not expose any information that we don't want to.</p>
<h2 id="heading-21-create-a-custom-result-filter">2.1. Create a Custom Result Filter</h2>
<p>Create a class: <code>MyModelValidationResultFilter</code>, and implement <code>IResultFilter</code> on it. Now we move ahead step-by-step to understand what we are doing.</p>
<h3 id="heading-211-when-the-model-is-valid">2.1.1. When the model is valid</h3>
<p>In case, the model is valid, execution must return immediately</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">if</span> (context.ModelState.IsValid)
    <span class="hljs-keyword">return</span>;
</code></pre>
<h3 id="heading-212-when-model-binding-fails">2.1.2. When model-binding fails</h3>
<p>Consider the following view model:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OrderViewModel</span>
{
    <span class="hljs-keyword">public</span> Int32 Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> Dictionary&lt;Int32, Int32&gt;? ProductQuantityMap { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>And the following action method:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OrdersController</span> : <span class="hljs-title">ControllerBase</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">Create</span>(<span class="hljs-params">OrderViewModel viewModel</span>)</span>
    {
        <span class="hljs-keyword">var</span> id = _orderService.Create(viewModel);
        <span class="hljs-keyword">return</span> StatusCode(Status201Created, id);
    }
}
</code></pre>
<p>Now let's say one of the following request payloads is provided to the above-mentioned API:</p>
<ul>
<li><p><code>null</code></p>
</li>
<li><p><code>{ null }</code></p>
</li>
<li><p><code>{ "null": "" }</code></p>
</li>
</ul>
<p>In all these scenarios, the model-binding will fail. In the first case, upon model-binding failure, the value of the key is empty, <code>""</code> and in the second and third cases, the value of the key is the <code>$</code> sign. To handle these cases we have used the following code:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">//When model-binding fails because input is an invalid JSON</span>
<span class="hljs-keyword">if</span> (modelStateDictionary.Any(
        pair =&gt; pair.Key == DollarSign ||
        String.IsNullOrEmpty(pair.Key)))
{
    problemDetails.Detail = RequestFailedModelBinding;
    context.Result = GetBadRequestObjectResult(problemDetails);
    <span class="hljs-keyword">return</span>;
}
</code></pre>
<p><mark>Take a gander at </mark> <a target="_blank" href="https://stackoverflow.com/questions/76401993/what-is-the-best-way-to-identify-that-a-model-binding-has-failed-in-asp-net-core"><mark>this StackOverflow question</mark></a>.</p>
<h3 id="heading-213-when-a-specific-property-binding-of-the-model-failed">2.1.3. When a specific property-binding of the model, failed</h3>
<p>Consider the following action method:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OrdersController</span> : <span class="hljs-title">ControllerBase</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">Create</span>(<span class="hljs-params">OrderViewModel viewModel</span>)</span>
    {
        <span class="hljs-keyword">var</span> id = _orderService.Create(viewModel);
        <span class="hljs-keyword">return</span> StatusCode(Status201Created, id);
    }
}
</code></pre>
<p>And consider the following request payloads, which are provided via Swagger/Postman:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">//1.</span>
{
    <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"productQuantityMap"</span>: <span class="hljs-literal">null</span>
}

<span class="hljs-comment">//2.</span>
{
    <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"productQuantityMap"</span>: {
        <span class="hljs-literal">null</span>
    }
}
</code></pre>
<p>The above-mentioned request payload will generate a model-validation error, because of the model-binding failure which will generate <code>"$.productQuantityMap"</code> as the error key. Now, to handle this scenario we have used the following code:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">//When a specific property-binding fails</span>
<span class="hljs-keyword">var</span> keyValuePair = modelStateDictionary.FirstOrDefault(pair =&gt; pair.Key.Contains(<span class="hljs-string">"$."</span>));
{
    <span class="hljs-keyword">var</span> propertyName = keyValuePair.Key.Split(Dot)[<span class="hljs-number">1</span>];
    problemDetails.Detail = String.IsNullOrEmpty(propertyName) ?
        RequestFailedModelBinding :
        String.Format(RequestPropertyFailedModelBinding, propertyName);
    context.Result = GetBadRequestObjectResult(problemDetails);
    <span class="hljs-keyword">return</span>;
}
</code></pre>
<h3 id="heading-214-when-model-validation-errors-occurs">2.1.4. When model validation error(s) occurs</h3>
<pre><code class="lang-csharp"><span class="hljs-comment">//When one of the input parameters failed model-validation</span>
<span class="hljs-keyword">var</span> invalidParams = <span class="hljs-keyword">new</span> List&lt;InvalidParam&gt;(modelStateDictionary.Count);
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> keyModelStatePair <span class="hljs-keyword">in</span> modelStateDictionary)
{
    <span class="hljs-keyword">var</span> key = keyModelStatePair.Key;
    <span class="hljs-keyword">var</span> modelErrors = keyModelStatePair.Value.Errors;
    <span class="hljs-keyword">if</span> (modelErrors <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span> &amp;&amp; modelErrors.Count &gt; <span class="hljs-number">0</span>)
    {
        IEnumerable&lt;InvalidParam&gt; invalidParam;
        <span class="hljs-keyword">if</span> (modelErrors.Count == <span class="hljs-number">1</span>)
        {
            invalidParam = modelErrors.Select(error =&gt; <span class="hljs-keyword">new</span> InvalidParam(keyModelStatePair.Key, <span class="hljs-keyword">new</span>[] { error.ErrorMessage }));
        }
        <span class="hljs-keyword">else</span>
        {
            <span class="hljs-keyword">var</span> errorMessages = <span class="hljs-keyword">new</span> String[modelErrors.Count];
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; modelErrors.Count; i++)
            {
                errorMessages[i] = modelErrors[i].ErrorMessage;
            }

            invalidParam = modelErrors.Select(error =&gt; <span class="hljs-keyword">new</span> InvalidParam(keyModelStatePair.Key, errorMessages));
        }

        invalidParams.AddRange(invalidParam);
    }
}

problemDetails.Detail = RequestParametersDidNotValidate;
problemDetails.Extensions[<span class="hljs-keyword">nameof</span>(invalidParams)] = invalidParams;
context.Result = GetBadRequestObjectResult(problemDetails);
</code></pre>
<p>This above-mentioned piece of code handles model validation error(s).</p>
<h2 id="heading-22-test-the-custom-result-filter">2.2. Test the Custom Result Filter</h2>
<p>For unit testing, I follow the naming convention suggested by Steve "Ardalis" in <a target="_blank" href="https://ardalis.com/unit-test-naming-convention/">this article</a>. Here is <a target="_blank" href="https://github.com/phougatv/web-api-fundamentals/blob/master/test/ErrorResponse/ViaFilterAndMiddlewareTest/Filters/MyModelValidationResultFilterTest/OnResultExecutingShould.cs">the link to the unit-test cases</a> of <code>MyModelValidationResultFilter</code>.</p>
<h1 id="heading-3-use-exception-middleware-to-handle-all-exceptions">3. Use Exception Middleware to handle all exceptions</h1>
<p>For a detailed explanation, visit <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-8.0">handling errors in ASP.NET Core Web API</a>. Here we will handle errors using an <code>ErrorsController</code>. We will need to follow these 2 steps:</p>
<p><strong>Step 1:</strong> Create <code>ErrorsController</code> with 2 action methods: <code>HandleErrorDevelopment</code>, for catering requests in development environments and <code>HandleError</code>, for catering requests in non-development environments.</p>
<p>The <code>HandleErrorDevelopment</code> action method will be invoked when an exception is thrown in the development environment. It handles custom as well as framework exceptions based on the value of <code>exceptionHandlerFeature</code> and <code>exceptionHandlerFeature.Error</code>.</p>
<p>The <code>HandleError</code> action method will be invoked when an exception is thrown in the non-development environment. In case of custom exceptions, it will return an appropriate response to the client and for all other exceptions, it will return a <code>ProblemDetails</code> instance with <code>Internal Server Error</code> Response.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Microsoft.AspNetCore.Authorization;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Diagnostics;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Http;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc;
<span class="hljs-keyword">using</span> WebApi.ErrorResponse.ViaFilterAndMiddleware.Exceptions;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">static</span> Microsoft.AspNetCore.Http.StatusCodes;

[<span class="hljs-meta">Route(<span class="hljs-meta-string">"api/[controller]"</span>)</span>]
[<span class="hljs-meta">ApiController</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ErrorsController</span> : <span class="hljs-title">ControllerBase</span>
{
    [<span class="hljs-meta">Route(<span class="hljs-meta-string">"error-development"</span>)</span>]
    [<span class="hljs-meta">ApiExplorerSettings(IgnoreApi = true)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">HandleErrorDevelopment</span>(<span class="hljs-params">[FromServices] IHostEnvironment hostEnvironment</span>)</span>
    {
        <span class="hljs-keyword">if</span> (hostEnvironment <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span> &amp;&amp; !hostEnvironment.IsDevelopment())
            <span class="hljs-keyword">return</span> NotFound();

        <span class="hljs-keyword">var</span> exceptionHandlerFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;()!;
        <span class="hljs-keyword">if</span> (exceptionHandlerFeature <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span> ||
            exceptionHandlerFeature.Error <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span>)
        {

            <span class="hljs-comment">/*
              Returns internal server error in case this
              action method is called but "exceptionHandlerFeature" or
              "exceptionHandlerFeature.Error" is null
            */</span>
            <span class="hljs-keyword">return</span> Problem(
                title: <span class="hljs-string">"Internal Server Error"</span>,
                detail: <span class="hljs-string">"You are on your own, now start debugging."</span>,
                statusCode: Status500InternalServerError);            
        }

        <span class="hljs-comment">//Handles custom exceptions</span>
        <span class="hljs-keyword">if</span> (exceptionHandlerFeature.Error <span class="hljs-keyword">is</span> MyExceptionBase myException)
        {
            <span class="hljs-keyword">return</span> Problem(
                detail: myException.Detail,
                title: myException.Title,
                statusCode: myException.StatusCode,
                instance: exceptionHandlerFeature.Path);
        }

        <span class="hljs-comment">//Handles framework exceptions</span>
        <span class="hljs-keyword">return</span> Problem(
            detail: exceptionHandlerFeature.Error.StackTrace,
            title: exceptionHandlerFeature.Error.Message,
            statusCode: Status500InternalServerError,
            instance: exceptionHandlerFeature.Path);
    }

    [<span class="hljs-meta">Route(<span class="hljs-meta-string">"error"</span>)</span>]
    [<span class="hljs-meta">ApiExplorerSettings(IgnoreApi = true)</span>]
    [<span class="hljs-meta">AllowAnonymous</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">HandleError</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> exceptionHandlerFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;()!;
        <span class="hljs-keyword">if</span> (exceptionHandlerFeature <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span> &amp;&amp;
            exceptionHandlerFeature.Error <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span> &amp;&amp;
            exceptionHandlerFeature.Error <span class="hljs-keyword">is</span> MyExceptionBase myException)
        {    <span class="hljs-comment">//&lt;--Only handles custom exceptions</span>
            <span class="hljs-keyword">return</span> Problem(
                detail: myException.Detail,
                title: myException.Title,
                statusCode: myException.StatusCode,
                instance: exceptionHandlerFeature.Path);
        }

        <span class="hljs-keyword">return</span> Problem(    <span class="hljs-comment">//&lt;--Handles all other exceptions</span>
            title: <span class="hljs-string">"Internal Server Error"</span>,
            detail: <span class="hljs-string">"Internal server error occurred, contact your admin."</span>,
            statusCode: Status500InternalServerError);
    }
}
</code></pre>
<p><strong>Step 2:</strong> Configure <code>UseExceptionHandler</code> middleware to call specific action methods of an <code>ErrorController</code>.</p>
<blockquote>
<p>⚠️ Be very cautious when passing the development error API path to the exception middleware, triple check it. This <code>app.UseExceptionHandler("/error-development");</code> must be inside the block which will be invoked in a development environment only.</p>
</blockquote>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

<span class="hljs-comment">// Add services to the container.</span>

<span class="hljs-keyword">var</span> app = builder.Build();

<span class="hljs-comment">// Configure the HTTP request pipeline.</span>
<span class="hljs-keyword">if</span> (app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(<span class="hljs-string">"/error-development"</span>);
    <span class="hljs-comment">//Configure middleware that are specific to development environment.</span>
}
<span class="hljs-keyword">else</span>
{
    app.UseExceptionHandler(<span class="hljs-string">"/error"</span>);
    <span class="hljs-comment">//Configure middleware that are specific to non-development environment.</span>
}

<span class="hljs-comment">/*
    Configure middleware that are common to both
    development and non-development environments
 */</span>

app.Run();
</code></pre>
<h1 id="heading-4-my-take-on-it">4. My Take on it</h1>
<p>I would prefer the Result Filter and exception middleware over custom <code>ProblemDetailsFactory</code>, to handle error response in ASP.NET Core Web API. Your preference can be completely different which is perfectly fine. Because it depends on what the client/user finds more appealing.</p>
<p>You may ask, why do I prefer Result Filter and exception middleware over custom <code>ProblemDetailsFactory</code>?</p>
<p>✅In case of model validation failures, the Result Filter gives more control over the execution as well as the structure of the result when compared to the <code>ValidationProblemDetails</code> instance of the <code>ProblemDetailsFactory</code>. With more control comes more responsibilities, so make sure to write enough unit-test cases to cover edge cases as well.</p>
<p>❌ What if you want to change the structure of the <code>error</code> property in the <code>ValidationProblemDetails</code> instance? Bad news, it cannot be done, neither it can be removed. For more details about it read <a target="_blank" href="https://phougatv.hashnode.dev/part-2-using-custom-problemdetailsfactory#heading-6-a-few-not-so-appealing-points-as-per-my-requirement">this</a>.</p>
<p>❌ And if you want to use custom <code>ProblemDetailsFactory</code>, you will be enforced to return an instance of <code>ValidationProblemDetails</code> instance upon model validation failure, which will enforce the previous point.</p>
]]></content:encoded></item><item><title><![CDATA[Using Custom "ProblemDetailsFactory" (2/3)]]></title><description><![CDATA[Create custom Problem Details Factory in ASP.NET Core]]></description><link>https://evolving-engineer.hashnode.dev/using-custom-problemdetailsfactory-23</link><guid isPermaLink="true">https://evolving-engineer.hashnode.dev/using-custom-problemdetailsfactory-23</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[error handling]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Problem Details]]></category><category><![CDATA[Model Validation]]></category><dc:creator><![CDATA[Vedant Phougat]]></dc:creator><pubDate>Tue, 04 Jul 2023 15:59:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688742441428/1a7fbf98-a7c0-42ae-9c71-a608c7773e59.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article shows, how one can return a structured response from an ASP.NET web API in case of errors (exceptions &amp; model validations). One way to do that is by using custom <code>ProblemDetailsFactory</code>.</p>
<h1 id="heading-1-what-is-problemdetailsfactory">1. What is <code>ProblemDetailsFactory</code>?</h1>
<p><a target="_blank" href="https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Infrastructure/ProblemDetailsFactory.cs">ProblemDetailsFactory</a> is an abstract class that defines 2 abstract methods:</p>
<ul>
<li><p><code>CreateProblemDetails</code> that returns an instance of <code>ProblemDetails</code></p>
</li>
<li><p><code>CreateValidationProblemDetails</code> that returns an instance of <code>ValidationProblemDetails</code></p>
</li>
</ul>
<blockquote>
<p>ValidationProblemDetails is ProblemDetails for validation errors</p>
</blockquote>
<p>These 2 methods are used to generate all instances of <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails">ProblemDetails</a> and <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.validationproblemdetails">ValidationProblemDetails</a>. These instances configure defaults, based on values specified in the <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-7.0#use-apibehavioroptionsclienterrormapping">ApiBehaviorOptions</a>.</p>
<p>An implementation of <a target="_blank" href="https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Infrastructure/ProblemDetailsFactory.cs">ProblemDetailsFactory</a> is provided by Microsoft that goes by the name: <a target="_blank" href="https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Infrastructure/DefaultProblemDetailsFactory.cs">DefaultProblemDetailsFactory</a>.</p>
<h1 id="heading-2-how-is-problemdetailsfactory-related-to-error-response">2. How is <code>ProblemDetailsFactory</code> related to error response?</h1>
<p>As per <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-7.0#client-error-response">MSDN</a></p>
<blockquote>
<p>An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to produce a ProblemDetails instance</p>
</blockquote>
<p>The <code>ProblemDetails</code> response is returned by calling the <code>CreateProblemDetails</code> method of <code>ProblemDetailsFactory</code> class in the following cases:</p>
<ul>
<li><p>Any <code>IActionResult</code> type that returns an HTTP status code of 400 or higher will be treated as an error result and a <code>ProblemDetails</code> instance will be returned as a response. For example, <code>BadRequest</code>, <code>NotFound</code>, <code>StatusCode(StatusCodes.Status500InternalServerError)</code> etc.</p>
</li>
<li><p>When an unhandled exception is thrown.</p>
</li>
<li><p>When we return <code>Problem()</code>, with or without params, from our controller's action methods.</p>
</li>
</ul>
<p>Similarly <code>ValidationProblemDetails</code> response is returned by calling the <code>CreateValidationProblemDetails</code> method of <code>ProblemDetailsFactory</code> class in the following cases:</p>
<ul>
<li><p>The <code>[ApiController]</code> attribute at the top of our web API controllers, automatically triggers an HTTP 400 response when model validation errors occur. And the default response type for an HTTP 400 response is <code>ValidationProblemDetails</code>. This response is generated by calling the <code>InvalidModelStateResponseFactory</code>, which then calls the <code>CreateValidationProblemDetails</code> method of the <code>ProblemDetailsFactoy</code>.</p>
</li>
<li><p>When we return <code>ValidationProblem()</code>, with or without params, from our controller's action methods.</p>
</li>
</ul>
<h1 id="heading-3-why-do-we-need-to-write-our-own-problemdetailsfactory">3. Why do we need to write our own <code>ProblemDetailsFactory</code> ?</h1>
<p>Although an <em>error result</em> is defined as a result with an HTTP status code of 400 or higher and for web API controllers, MVC transforms an error result to produce a <code>ProblemDetails</code> instance, <mark>ASP.NET Core doesn't produce a standardized error payload when an unhandled exception occurs</mark> - <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0#produce-a-problemdetails-payload-for-exceptions">as per "Produce a ProblemDetails payload for exceptions" on MSDN</a>.</p>
<p>Using custom <code>ProblemDetailsFactory</code> along with exception middleware we can easily tackle unhandled and custom exceptions as well as model-validation errors and return a structured and consistent response from across the application. And the code that makes all this happen is centralized, so we know where to look when we face any problem with our error responses.</p>
<h1 id="heading-4-how-to-handle-custom-and-framework-level-exceptions">4. How to handle custom and framework-level exceptions?</h1>
<h2 id="heading-41-custom-problem-details-factory">4.1. Custom Problem Details Factory</h2>
<p>First, create a class, <code>MyProblemDetailsFactory</code> inheriting <code>ProblemDetailsFactory</code> class which enforces you to implement two abstract methods, one of them is <code>CreateProblemDetails</code>.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Microsoft.AspNetCore.Diagnostics;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Http;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc.Infrastructure;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc.ModelBinding;

<span class="hljs-keyword">internal</span> <span class="hljs-keyword">sealed</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MyProblemDetailsFactory</span> : <span class="hljs-title">ProblemDetailsFactory</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> ProblemDetails <span class="hljs-title">CreateProblemDetails</span>(<span class="hljs-params">
        HttpContext httpContext,
        Int32? statusCode = <span class="hljs-literal">null</span>,
        String? title = <span class="hljs-literal">null</span>,
        String? type = <span class="hljs-literal">null</span>,
        String? detail = <span class="hljs-literal">null</span>,
        String? instance = <span class="hljs-literal">null</span></span>)</span>
    {
        ProblemDetails problemDetails;
        <span class="hljs-keyword">var</span> exceptionHandlerFeature = httpContext.Features.Get&lt;IExceptionHandlerFeature&gt;();
        <span class="hljs-keyword">if</span> (exceptionHandlerFeature <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span> &amp;&amp;
            exceptionHandlerFeature.Error <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span> &amp;&amp;
            exceptionHandlerFeature.Error <span class="hljs-keyword">is</span> MyExceptionBase myException)
        {   <span class="hljs-comment">//&lt;-- Custom exception handler</span>
            httpContext.Response.StatusCode = myException.StatusCode;       <span class="hljs-comment">//&lt;-- Overrides the default 500 status code</span>
            problemDetails = <span class="hljs-keyword">new</span> ProblemDetails
            {
                Detail = myException.Detail,
                Instance = exceptionHandlerFeature.Path,
                Status = myException.StatusCode,
                Title = myException.Title
            };
        }
        <span class="hljs-keyword">else</span>
        {   <span class="hljs-comment">//&lt;-- Default ProblemDetails instance, used for unhandled exceptions</span>
            statusCode = statusCode ?? StatusCodes.Status500InternalServerError;
            detail = detail ?? <span class="hljs-string">"An error occurred, connect with your administrator."</span>;
            title = title ?? <span class="hljs-string">"Internal Server Error"</span>;
            httpContext.Response.StatusCode = statusCode.Value;
            problemDetails = <span class="hljs-keyword">new</span> ProblemDetails
            {
                Detail = detail,
                Instance = instance,
                Status = statusCode,
                Title = title,
                Type = type
            };
        }

        <span class="hljs-keyword">return</span> problemDetails;
    }
}
</code></pre>
<h2 id="heading-42-exception-handling-middleware">4.2. Exception Handling Middleware</h2>
<p>Configure <code>UseExceptionHandler()</code> middleware to call the specific action methods of <code>ErrorsController</code>.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

<span class="hljs-comment">// Add services to the container.</span>
builder.Services.AddControllers();
builder.Services.AddSingleton&lt;ProblemDetailsFactory, MyProblemDetailsFactory&gt;();    <span class="hljs-comment">//&lt;-- Register custom ProblemDetailsFactory</span>

<span class="hljs-comment">// Configure the HTTP request pipeline.</span>
<span class="hljs-keyword">if</span> (app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(<span class="hljs-string">"/error-development"</span>);
    <span class="hljs-comment">//Configure middleware specific to development environment</span>
}
<span class="hljs-keyword">else</span>
{
    app.UseExceptionHandler(<span class="hljs-string">"/error"</span>);
    <span class="hljs-comment">//Configure middleware specific to non-development environments</span>
}

<span class="hljs-comment">//Configure middleware common to both development and non-development environments</span>

app.Run();
</code></pre>
<h2 id="heading-43-errors-controller">4.3. Errors Controller</h2>
<p>A few points to note about the ErrorsController:</p>
<ul>
<li><p>There is no <code>Route()</code> attribute on the <code>ErrorController</code>, unlike other controllers. Because exception middleware will call a route of <code>/error-development</code> in the Development environment and a route of <code>/error</code> in non-Development environments.</p>
</li>
<li><p>Don't mark the error handler action method with HTTP method attributes, such as <code>HttpGet</code>. Explicit verbs prevent some requests from reaching the action method.</p>
</li>
<li><p>The attribute <code>[ApiExplorerSettings(IgnoreApi = true)]</code> excludes the error handler action from the app's <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-6.0"><strong>Swagger / OpenAPI</strong></a> specification.</p>
</li>
<li><p>Allow anonymous access to the method if unauthenticated users should see the error.</p>
</li>
</ul>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Microsoft.AspNetCore.Authorization;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Diagnostics;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc;

[<span class="hljs-meta">ApiController</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ErrorsController</span> : <span class="hljs-title">ControllerBase</span>
{
    [<span class="hljs-meta">Route(<span class="hljs-meta-string">"error-development"</span>)</span>]
    [<span class="hljs-meta">ApiExplorerSettings(IgnoreApi = true)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">HandleErrorDevelopment</span>(<span class="hljs-params">[FromServices] IHostEnvironment hostEnvironment</span>)</span>
    {
        <span class="hljs-keyword">if</span> (hostEnvironment <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span> &amp;&amp; !hostEnvironment.IsDevelopment())
            <span class="hljs-keyword">return</span> NotFound();

        <span class="hljs-keyword">var</span> exceptionHandlerFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;()!;

        <span class="hljs-keyword">return</span> Problem(
            detail: exceptionHandlerFeature.Error.StackTrace,
            title: exceptionHandlerFeature.Error.Message,
            instance: exceptionHandlerFeature.Path);
    }

    [<span class="hljs-meta">Route(<span class="hljs-meta-string">"error"</span>)</span>]
    [<span class="hljs-meta">ApiExplorerSettings(IgnoreApi = true)</span>]
    [<span class="hljs-meta">AllowAnonymous</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">HandleError</span>(<span class="hljs-params"></span>)</span> =&gt; Problem();
}
</code></pre>
<h1 id="heading-5-how-to-handle-model-validation-failures">5. How to handle model validation failures?</h1>
<p>This is the same class: <code>MyProblemDetailsFactory</code>, but it only contains the overridden <code>CreateValidationProblemDetails</code> method. For full code, you can put both methods: <code>CreateProblemDetails</code> and <code>CreateValidationProblemDetails</code> in the same class, the one that inherits <code>ProblemDetailsFactory</code> class.</p>
<p>This will handle both, the inbuilt and custom validation errors.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Microsoft.AspNetCore.Diagnostics;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Http;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc.Infrastructure;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc.ModelBinding;

<span class="hljs-keyword">internal</span> <span class="hljs-keyword">sealed</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MyProblemDetailsFactory</span> : <span class="hljs-title">ProblemDetailsFactory</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> ValidationProblemDetails <span class="hljs-title">CreateValidationProblemDetails</span>(<span class="hljs-params">
        HttpContext httpContext,
        ModelStateDictionary modelStateDictionary,
        Int32? statusCode = <span class="hljs-literal">null</span>,
        String? title = <span class="hljs-literal">null</span>,
        String? type = <span class="hljs-literal">null</span>,
        String? detail = <span class="hljs-literal">null</span>,
        String? instance = <span class="hljs-literal">null</span></span>)</span>
    {
        ArgumentNullException.ThrowIfNull(modelStateDictionary);

        statusCode ??= StatusCodes.Status400BadRequest;
        <span class="hljs-keyword">var</span> validationProblemDetails = <span class="hljs-keyword">new</span> ValidationProblemDetails(modelStateDictionary)
        {
            Status = statusCode,
            Type = type,
            Detail = detail,
            Instance = instance
        };
        <span class="hljs-keyword">if</span> (title <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span>)
        {
            <span class="hljs-comment">// For validation problem details, don't overwrite the default title with null.</span>
            validationProblemDetails.Title = title;
        }

        <span class="hljs-keyword">return</span> validationProblemDetails;
    }
}
</code></pre>
<h1 id="heading-6-a-few-not-so-appealing-points-as-per-my-requirement">6. A few, not so Appealing Points as per my requirement</h1>
<ul>
<li><p>In case of model validation failure, the errors will be displayed in a particular way and that way cannot be modified. The <code>Errors</code> property is of type <code>IDictionary&lt;String, String[]&gt;</code> and one cannot change its type or remove it from the <code>Extensions</code> property of <code>ProblemDetails</code> instance (<em>or at least I don't know it yet</em>).</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"One or more validation errors occurred."</span>,
    <span class="hljs-attr">"status"</span>: <span class="hljs-number">400</span>,
    <span class="hljs-attr">"errors"</span>: {
      <span class="hljs-attr">"id"</span>: [
        <span class="hljs-string">"Must be greater than 0."</span>
      ]
    }
  }
</code></pre>
<p>  For example, if I want to present errors in the following way, then it cannot be done.</p>
<pre><code class="lang-json">  {
      <span class="hljs-attr">"title"</span>: <span class="hljs-string">"One or more validation errors occurred."</span>,
      <span class="hljs-attr">"status"</span>: <span class="hljs-number">400</span>,
      <span class="hljs-attr">"errors"</span>: [
          {
              <span class="hljs-attr">"name"</span>: <span class="hljs-string">"id"</span>,
              <span class="hljs-attr">"reason"</span>: <span class="hljs-string">"Must be greater than 0."</span>
          }
      ]
  }
</code></pre>
<p>  To do this there is a workaround and it is certainly not pretty, as you can see the empty <code>errors</code> property exists.</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"One or more validation errors occurred."</span>,
    <span class="hljs-attr">"status"</span>: <span class="hljs-number">400</span>,
    <span class="hljs-attr">"invalidParams"</span>: [
        {
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"id"</span>,
            <span class="hljs-attr">"reason"</span>: <span class="hljs-string">"Must be greater than 0."</span>
        }
    ],
    <span class="hljs-attr">"errors"</span>: {}
  }
</code></pre>
</li>
</ul>
<p><strong>NOTE:</strong> <mark>In case you don't want to invoke the </mark> <code>ProblemDetailsFactory</code> <mark> methods by default, then read </mark> <a target="_blank" href="https://github.com/dotnet/aspnetcore/issues/12893"><mark>this</mark></a><mark>.</mark></p>
<h1 id="heading-7-references">7. References</h1>
<ul>
<li><p><a target="_blank" href="https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Infrastructure/DefaultProblemDetailsFactory.cs">DefaultProblemDetailsFactory by ASP.NET Core - MSDN</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0#implement-problemdetailsfactory-1">Implement <code>ProblemDetailsFactory</code> - MSDN</a></p>
</li>
<li><p><a target="_blank" href="http://stevenmaglio.blogspot.com/2019/12/create-custom-problemdetailsfactory.html">Create a Custom ProblemDetailsFactory</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[A Short Intro to "ProblemDetails" (1/3)]]></title><description><![CDATA[Return problem details instance when error occurs in a REST API]]></description><link>https://evolving-engineer.hashnode.dev/a-short-intro-to-problemdetails-13</link><guid isPermaLink="true">https://evolving-engineer.hashnode.dev/a-short-intro-to-problemdetails-13</guid><category><![CDATA[ProblemDetails]]></category><category><![CDATA[C#]]></category><category><![CDATA[ASP.NET]]></category><category><![CDATA[Web API]]></category><dc:creator><![CDATA[Vedant Phougat]]></dc:creator><pubDate>Fri, 09 Jun 2023 16:12:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688742323094/1bfb5a98-2ffd-4519-9f62-53410f64bda3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-definition">1. Definition</h1>
<p>For in-depth knowledge, visit: <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc7807">Problem Details for HTTP APIs</a> by the Internet Engineering Task Force (IETF).</p>
<p>This definition is borrowed from the article linked before:</p>
<blockquote>
<p><em>ProblemDetails</em> is a way to carry, machine-readable details of errors in an HTTP response, to avoid the need to define new error formats for HTTP APIs.</p>
</blockquote>
<p>This one is translated to something that I can understand and remember:</p>
<blockquote>
<p><em>ProblemDetails</em> instance is an industry-standard error response which can help non-human consumers of HTTP APIs to understand the cause of the error in a better way and/or steps that can be taken to resolve it.</p>
</blockquote>
<h1 id="heading-2-media-type">2. Media-type</h1>
<ul>
<li><p>JSON: <code>"application/problem+json"</code></p>
</li>
<li><p>XML: <code>"application/problem+xml"</code></p>
</li>
</ul>
<h1 id="heading-3-why-return-a-problemdetails-instance">3. Why return a <code>ProblemDetails</code> Instance?</h1>
<blockquote>
<p>ProblemDetails instance represents errors in an HTTP API. This can help non-human consumers of the HTTP API to understand the error and then take steps to correct it.</p>
</blockquote>
<p>HTTP status codes are sometimes not sufficient to convey enough information about an error to be helpful. While humans can be informed about the nature of the problem with an HTML response body (parsed with the help of web browsers), non-human consumers of so-called "HTTP APIs" are usually not.</p>
<p>ProblemDetails instance helps in informing the non-human consumers of "HTTP APIs" about the nature of the problem returned. So, API clients can be informed of:</p>
<ul>
<li><p>The high-level error class (using the status code)</p>
</li>
<li><p>The finer-grained details of the problem (using the <em>ProblemDetails</em>)</p>
</li>
</ul>
<p>after which they can read and treat this <em>ProblemDetails</em> response appropriately.</p>
<h1 id="heading-4-members-of-a-problemdetails-instance">4. Members of a <code>ProblemDetails</code> Instance</h1>
<p>Consider the following JSON object, that we will use to describe the members of the ProblemDetails instance:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"type"</span>: <span class="hljs-string">"https://example.com/not-found"</span>,
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Not Found"</span>,
    <span class="hljs-attr">"status"</span>: <span class="hljs-number">404</span>,
    <span class="hljs-attr">"detail"</span>: <span class="hljs-string">"The resource you requested does not exist."</span>,
    <span class="hljs-attr">"instance"</span>: <span class="hljs-string">"api/orders/3"</span>
}
</code></pre>
<ul>
<li><p><code>type: String</code>: <em>A URI reference that identifies the problem type</em>.</p>
<p>  This property is optional, but it is recommended that you use it to provide a standard way to identify errors. When the value of this property is <strong><mark>NOT</mark></strong> <code>about:blank</code>, it should point to a document that provides human-readable documentation for the problem type.</p>
</li>
<li><p><code>title: String</code>: <em>A short, human-readable summary of the problem type</em>.</p>
<p>  It <mark>SHOULD NOT</mark> change from occurrence to occurrence of the problem, except for purposes of localization. For example, <code>"title": "Not Found"</code> is a short, human-readable summary of the problem type, but it does not go into detail (for its explanation we have <code>detail</code>).</p>
<ul>
<li><p>Use the same title for the same problem type, even if the error occurs in different places.</p>
</li>
<li><p>Keep it short.</p>
</li>
</ul>
</li>
<li><p><code>status: Int32</code>: <em>The HTTP status code generated by the origin server for this occurrence of the problem</em>. For details visit - <a target="_blank" href="https://www.rfc-editor.org/rfc/rfc9110.html#name-status-codes">Status Codes</a>.</p>
</li>
<li><p><code>detail: String</code>: <em>A human-readable explanation specific to this occurrence of the problem</em>.</p>
<p>  It MAY be used to provide additional information about the error, such as the cause of the error or steps that can be taken to resolve the error. For example, <code>"detail": "The resource you requested does not exist."</code>, provides more information about the error, such as the possible cause of the error.</p>
<ul>
<li><p>Use human-readable/plain language that is easy to understand.</p>
</li>
<li><p>Be specific.</p>
</li>
<li><p>Avoid technical jargon.</p>
</li>
<li><p>Provide as much information as possible about the error.</p>
</li>
</ul>
</li>
<li><p><code>instance: String</code>: <em>A URI reference that identifies the specific occurrence of the problem</em>.</p>
<p>  It MAY be used to provide additional information about the error, such as the ID of the resource that was not found or the timestamp of the error. For example, <code>"instance": "api/orders/7</code>, this is the URI of the order that was not found. The <code>instance</code> property is a useful way to provide information about an error. This can be helpful for users who are trying to understand why an error occurred. It can also be helpful for developers who are trying to debug and fix errors.</p>
<ul>
<li><p>Use a unique URI for each occurrence of the problem.</p>
</li>
<li><p>Use a URI that is meaningful to the user or developer.</p>
</li>
<li><p>Avoid using URIs that are too long or complex.</p>
</li>
</ul>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Custom Validation Attributes]]></title><description><![CDATA[How to create custom validation attributes in ASP.NET Core to enforce rules and improve the security and code reusability.]]></description><link>https://evolving-engineer.hashnode.dev/custom-validation-attributes</link><guid isPermaLink="true">https://evolving-engineer.hashnode.dev/custom-validation-attributes</guid><category><![CDATA[C#]]></category><category><![CDATA[asp.net core]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Custom Validation Attribute]]></category><category><![CDATA[ASP.NET 6]]></category><dc:creator><![CDATA[Vedant Phougat]]></dc:creator><pubDate>Fri, 02 Jun 2023 17:31:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cAY9X4rPG3g/upload/613ac078ed61f380f380aefa8b1e7a39.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-introduction">1. Introduction</h1>
<p>It describes the why and how to create custom validation attributes. For details refer to the official documentation of <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-7.0">Model Validation in ASP.NET Core MVC and Razor Pages</a>.</p>
<h1 id="heading-2-why-do-we-need-them">2. Why do we need them?</h1>
<p>We need custom validation attributes for scenarios that the built-in validation attributes don't handle. Custom validation attributes are a powerful way to enforce the rules in our ASP.NET Web APIs.</p>
<p>A few benefits of using custom validation attributes:</p>
<ul>
<li><p>They help in improving the security of the web API.</p>
</li>
<li><p>They make sure that the data that is submitted to the web API is valid.</p>
</li>
<li><p>They make your code reusable - as the validation logic is written once and then can be used any number of times.</p>
</li>
</ul>
<h1 id="heading-3-naming-them">3. Naming them</h1>
<p>The naming of custom validation attributes is an important aspect because it helps to communicate the purpose of the attribute to other developers without, them needing to dig into its logic.</p>
<p>Consider, we have to create a custom validation attribute that checks if the value is greater than 0. The possible names of the attributes are:</p>
<ul>
<li><p>GreaterThanZeroValidationAttribute</p>
</li>
<li><p>PositiveIntegerValidationAttribute</p>
</li>
<li><p>NaturalNumberValidationAttribute</p>
</li>
</ul>
<p>These names are descriptive that accurately reflect the purpose of the attribute. They are also short and do not contain any abbreviations or acronyms. I will choose <code>GreaterThanZeroValidationAttribute</code> as the name effortlessly conveys its purpose to the reader.</p>
<h1 id="heading-4-how-to-create-one">4. How to create one?</h1>
<p>Create a class <code>GreaterThanZeroValidationAttribute</code> that inherits from <code>ValidationAttributes</code> and override its <code>IsValid</code> method.</p>
<p>The <code>IsValid</code> method accepts an object named <code>value</code>, which is the input to be validated. An overload also accepts a <code>ValidationContext</code> object, which provides additional information, such as the model instance created by model binding.</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">AttributeUsage(AttributeTarget.Property | AttributeTarget.Parameter)</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GreaterThanZeroValidationAttribute</span> : <span class="hljs-title">ValidationAttribute</span>
{
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> ValidationResult? IsValid(Object? <span class="hljs-keyword">value</span>, ValidationContext validationContext)
    {
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">value</span> <span class="hljs-keyword">is</span> Int32 id &amp;&amp; id &gt; <span class="hljs-number">1</span>)
            <span class="hljs-keyword">return</span> ValidationResult.Success;

        <span class="hljs-keyword">var</span> errorMessage = String.Format(<span class="hljs-string">"{0} must be greater than 0."</span>, validationContext.MemberName!);
        <span class="hljs-keyword">var</span> result = <span class="hljs-keyword">new</span> ValidationResult(errorMessage);

        <span class="hljs-keyword">return</span> result;
    }
}
</code></pre>
<p><code>AttributeUsage</code> controls how the custom validation attribute class is used. For details visit <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.attributeusageattribute?view=net-7.0">AttributeUsageAttribute Class</a>.</p>
<p><code>AttributeTarget.Property | AttributeTarget.Parameter</code> states what the class can target - properties &amp; parameters, in this case. If <code>[GreaterThanZeroValidation]</code> is used on anything else, it will produce a compilation error. For details visit <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.attributetargets?view=net-7.0">AttributeTarget Enum</a>.</p>
<h1 id="heading-5-usage">5. Usage</h1>
<h2 id="heading-51-when-the-target-is-a-parameter">5.1 When the target is a parameter</h2>
<p>OrderController.cs</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">ApiController</span>]
[<span class="hljs-meta">Route(<span class="hljs-meta-string">"api/[controller]"</span>)</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OrderController</span> : <span class="hljs-title">ControllerBase</span>
{
    [<span class="hljs-meta">HttpGet(<span class="hljs-meta-string">"{id}"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">GetByIdAsync</span>(<span class="hljs-params">[GreaterThanZeroValidation] Int32 id</span>)</span>
    {
        <span class="hljs-comment">//fetch the order using id, asynchronously.</span>
    }
}
</code></pre>
<h2 id="heading-52-when-the-target-is-a-property-of-a-class">5.2 When the target is a property of a class</h2>
<p>OrderViewModel.cs</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OrderViewModel</span>
{
    [<span class="hljs-meta">GreaterThanZeroIntegerValidation</span>]
    <span class="hljs-keyword">public</span> Int32 Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> Dictionary&lt;Int32, Int32&gt; ProductQuantityMap { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-literal">null</span>!;
}
</code></pre>
<p>OrderController.cs</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">HttpPost</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">CreateAsync</span>(<span class="hljs-params">OrderViewModel viewModel</span>)</span>
{
    <span class="hljs-comment">//Do something with the viewModel.</span>
}
</code></pre>
]]></content:encoded></item></channel></rss>