<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zeeshan Mustafa on Medium]]></title>
        <description><![CDATA[Stories by Zeeshan Mustafa on Medium]]></description>
        <link>https://medium.com/@zeeshan.mustafa91?source=rss-f4f915f35f15------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LaDuG1-2GMI6S3N9iUUq5A.png</url>
            <title>Stories by Zeeshan Mustafa on Medium</title>
            <link>https://medium.com/@zeeshan.mustafa91?source=rss-f4f915f35f15------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:34:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zeeshan.mustafa91/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Docker Part 4: Running a .NET 8.0 Web API over HTTPS Inside Docker]]></title>
            <link>https://medium.com/@zeeshan.mustafa91/api-over-https-inside-docker-04dc0916e790?source=rss-f4f915f35f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/04dc0916e790</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[https-ssl]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Zeeshan Mustafa]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 07:00:23 GMT</pubDate>
            <atom:updated>2024-11-19T07:00:23.835Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Part 4: Running a .NET 8.0 Web API over HTTPS Inside Docker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1GYCt1U6ow1wHUN6pX_5w.png" /></figure><p>So far, we’ve taken our <a href="https://github.com/zeecorleone/colours.API/">Colours API </a>through a journey of containerization, multi-container orchestration, and data persistence with Docker volumes. If you’re just joining, I recommend checking out <a href="https://medium.com/@zeeshan.mustafa91/dockerize-net-8-0-web-api-cbb4b8426fdb">Part-1</a> where we first containerized our API:</p><p><a href="https://medium.com/@zeeshan.mustafa91/dockerize-net-8-0-web-api-cbb4b8426fdb">Docker Part 1: Containerize .NET 8.0 Web API</a></p><p>and <a href="https://medium.com/@zeeshan.mustafa91/docker-multi-container-setup-for-net-8-0-web-api-with-postgresql-and-redis-5147f1-5147f1f269cd">Part-2</a> for working with Docker Compose:</p><p><a href="https://medium.com/@zeeshan.mustafa91/docker-multi-container-setup-for-net-8-0-web-api-with-postgresql-and-redis-5147f1-5147f1f269cd">Docker Part 2: Multi-Container Setup for .NET 8.0 Web API with PostgreSQL and Redis</a></p><p>and <a href="https://medium.com/@zeeshan.mustafa91/docker-volumes-to-persist-logs-in-multi-container-net-8-0-web-api-bd5880971b17">Part-3</a>, where we used Docker Volumes for persistent storage:</p><p><a href="https://medium.com/@zeeshan.mustafa91/docker-volumes-to-persist-logs-in-multi-container-net-8-0-web-api-bd5880971b17">Docker Part 3: Using Volumes to Persist Logs in a Multi-Container .NET 8.0 Web API</a></p><p>In this fourth part, we’re focusing on a critical aspect of production-ready applications: R<strong>unning our API over HTTPS.</strong></p><p>We’ll first configure HTTPS in Docker with a self-signed certificate, ideal for development environments where you need HTTPS without relying on a public certificate authority. Let’s dive in!</p><h3>Why HTTPS Matters</h3><p>HTTPS is essential for secure communication, protecting data from interception and tampering. Running the Colours API over HTTPS will ensure our data is encrypted, even in a local development environment. This article’s setup is intended for development purposes, but the principles apply to production settings with certificates issued by trusted certificate authorities.</p><h3>Step 1: Generating a Self-Signed Certificate</h3><p>For this example, we’ll generate a self-signed certificate using Open SSL. You can also use PowerShell commands, but using Open SSL we can avoid storing the generated certificate in host certificates store.</p><p>This method works across different operating systems, including Windows, Mac, and Linux.</p><ol><li><strong>Install OpenSSL</strong> (if not already installed):<br>On Windows, you can download OpenSSL for Windows. Ensure you add OpenSSL to your system’s PATH, or specify the full path to openssl.exe in the following commands.<br><em>(Alternately, if you have Git installed, it already includes openssl.exe and you can use that. It is usually located at </em><em>C:\Program Files\Git\usr\bin)</em></li><li><strong>Create a directory for the certificate</strong>:<br>To keep it simple, I have created a new directory <em>“D:\temp-certs”</em> to hold the newly generated certificate and related keys etc.</li><li><strong>Generate the private key</strong>:<br>Run the following command to create a 2048-bit private key file:</li></ol><pre>openssl genrsa -out D:/temp-certs/colours-api-cert.key 2048</pre><p>4. <strong>Create a self-signed certificate</strong>: <br>Use the private key to generate a certificate valid for 1 years (365 days). Replace the -subj parameter as needed; here, we set it to localhost-colours-api:</p><pre>openssl req -x509 -new -nodes -key D:/temp-certs/colours-api-cert.key -sha256 -days 365 -out D:/temp-certs/colours-api-cert.cert -subj &quot;/CN=localhost-colours-api&quot;</pre><p>After this step, you should see two files in D:/temp-certs/:</p><ul><li>colours-api-cert.key: Your private key</li><li>colours-api-cert.cert: Your self-signed certificate</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*5O3SDIsy6S2z5xE50C3cuw.png" /></figure><p>4. <strong>Combine the certificate and key into a PFX file</strong>: <br>Next, create a PFX (PKCS #12) file. This command combines the .cert and .key files into a .pfx file with a specified password (123456 in this example; Please make sure you use a strong password):</p><pre>openssl pkcs12 -export -out D:/temp-certs/colours-api-cert.pfx -inkey D:/temp-certs/colours-api-cert.key -in D:/temp-certs/colours-api-cert.cert -passout pass:123456</pre><p>Now, your certificate is ready to be used with Docker, with all files stored in D:/temp-certs/. The .pfx file will be referenced in the Docker configuration. Here is how the content of your <em>“D:/temp-certs”</em> directory should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*Y6QdvgBYQccF-tTl9Tz2RQ.png" /></figure><h3>Step 2: Updating the Docker Compose Configuration</h3><p>With the self-signed certificate generated, let’s now update the docker-compose.yml file to support HTTPS.</p><ol><li><strong>Modify the API Service</strong>: <br>In the docker-compose.yml file, locate the api service section. Add a volume mapping to make the .pfx certificate file available inside the container, and update the environment variables to configure HTTPS.</li><li>Here’s what the updated api service section should look like:</li></ol><pre>#...other section...<br>services:<br>  api:<br>    image: modulez33/colours-api:3.0.0<br>    environment:<br>        - ASPNETCORE_ENVIRONMENT=Development<br>        - ASPNETCORE_URLS=http://+:5000;https://+:5001<br>        - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/colours-api-cert.pfx<br>        - ASPNETCORE_Kestrel__Certificates__Default__Password=123456<br>        - ConnectionStrings__Default=User ID=postgres;Password=123456;Server=postgres;Port=5432;Database=coloursdb;Pooling=true;<br>        - Redis__Host=redis<br>        - Redis__Port=6379<br>    volumes:<br>        - colours_api_logs_data:/app/logs <br>        - D:/temp-certs/:/https/<br>    ports:<br>        - &quot;5000:5000&quot;<br>        - &quot;5001:5001&quot;<br>    depends_on:<br>        - postgres<br>        - redis<br><br>#...other section...</pre><p>Here’s a breakdown of the changes made:</p><ul><li><strong>ASPNETCORE_URLS</strong>: Updated to expose HTTPS on port 5001.</li><li><strong>ASPNETCORE_Kestrel__Certificates__Default__Path</strong>: Set to the location of the .pfx certificate within the container (/https/colours-api-cert.pfx).</li><li><strong>ASPNETCORE_Kestrel__Certificates__Default__Password</strong>: Set to the password used when exporting the .pfx file (in this example, 123456).</li><li><strong>Volume Mapping</strong>: Added D:/temp-certs/colours-api-cert.pfx:/https/colours-api-cert.pfx, mapping the certificate from your local machine to the container.</li></ul><h3>Start the Services with Docker Compose</h3><p>Now let’s use Docker Compose to spin up the API along with PostgreSQL and Redis and Volumes mapping:</p><pre>docker-compose up</pre><p>This command will spin up three containers: the API, PostgreSQL, and Redis.</p><p>You should see something like following in your console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZLRhUV58ahP2pRlCmxh4w.png" /><figcaption>App listening on HTTPS</figcaption></figure><p>Now let’s call the API over https to prove it works.</p><p>I have created few colours over https url:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*ZndbNm_AGpuD5juW5KN8xw.png" /></figure><p>And I am able to list them over https url:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*cpb1-DqVndlrAyKRTGJ9vw.png" /></figure><h3>Conclusion</h3><p>Congratulations! We’ve just configured and consumed our .NET Web API hosted inside a container, over https.</p><p>Stay tuned for more beginner friendly articles.</p><p>Feel free to check out <a href="https://medium.com/@zeeshan.mustafa91/dockerize-net-8-0-web-api-cbb4b8426fdb"><em>Part 1</em> here</a>, <a href="https://medium.com/@zeeshan.mustafa91/docker-multi-container-setup-for-net-8-0-web-api-with-postgresql-and-redis-5147f1-5147f1f269cd">Part 2 here</a>, and <a href="https://medium.com/@zeeshan.mustafa91/docker-volumes-to-persist-logs-in-multi-container-net-8-0-web-api-bd5880971b17">Part 3 here</a>, if you missed it, and keep an eye out for the next part of this Docker series!</p><p>Happy coding : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04dc0916e790" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Part 3: Using Volumes to Persist Logs in a Multi-Container .NET 8.0 Web API]]></title>
            <link>https://medium.com/@zeeshan.mustafa91/docker-volumes-to-persist-logs-in-multi-container-net-8-0-web-api-bd5880971b17?source=rss-f4f915f35f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5880971b17</guid>
            <category><![CDATA[dotnet-8]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-volume]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <dc:creator><![CDATA[Zeeshan Mustafa]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 06:41:52 GMT</pubDate>
            <atom:updated>2024-11-14T06:41:52.474Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Part 3: Using Volumes to Persist Data in a Multi-Container .NET 8.0 Web API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*JBsUMxHWnEJjD9H8cR7FlQ.png" /></figure><p>In this article (<em>Part 3 </em>of the series), we continue our Docker journey by diving into <strong>Docker Volumes</strong>. In the first part of the series, we introduced containerization for a basic .NET 8.0 Web API. In Part 2, we extended that API with PostgreSQL and Redis, managing dependencies with Docker Compose. If you’re just joining us, feel free to check out Part 1:</p><p><a href="https://medium.com/@zeeshan.mustafa91/dockerize-net-8-0-web-api-cbb4b8426fdb">Docker Part 1: Containerize .NET 8.0 Web API</a></p><p>and Part 2:</p><p><a href="https://medium.com/@zeeshan.mustafa91/docker-multi-container-setup-for-net-8-0-web-api-with-postgresql-and-redis-5147f1-5147f1f269cd">Docker Part 2: Multi-Container Setup for .NET 8.0 Web API with PostgreSQL and Redis</a></p><p>In this article, we’ll explore a key Docker feature: <strong>volumes</strong>, which allow data to persist even when a container stops. We’ll demonstrate this using a logging example, where the API logs each request, and we can keep logs intact between container restarts.</p><h3>Why Volumes Matter in Docker</h3><p>By default, data within a Docker container is lost when the container is removed or restarted. This is important to understand for cases where you need data to persist, like when logging requests, saving files, or handling any data that must remain accessible long-term. Without volumes, any data stored in a container would be deleted when the container itself is removed.</p><p>In our example, we’ll configure Docker volumes to log all incoming requests to our Colours API and ensure that these logs are retained even if the container is stopped, restarted, or completely removed. This setup will demonstrate how Docker volumes enable data persistence across the container’s lifecycle.</p><h3>Step 1:</h3><h3>Setting Up Request Logging in the API</h3><p>In our example, we log every incoming request in the API to keep track of user activity. We added a middleware component to Program.cs to log these requests. Here’s how it looks:</p><pre>var logFilePath = Path.Combine(&quot;/app/logs&quot;, &quot;app.log&quot;);<br>var logDirectory = Path.GetDirectoryName(logFilePath);<br>if (!Directory.Exists(logDirectory))<br>    Directory.CreateDirectory(logDirectory!);<br><br>app.Use(async (context, next) =&gt;<br>{<br>    if (!context.Request.Path.StartsWithSegments(&quot;/swagger&quot;))<br>    {<br>        var logEntry = $&quot;{DateTime.Now}: {context.Request.Method} {context.Request.Path}&quot;;<br>        await File.AppendAllTextAsync(logFilePath, logEntry + &quot; \n\n&quot;);<br>    }<br>    await next();<br>});</pre><p>The middleware logs every request (except for Swagger UI requests) by appending a timestamp, HTTP method, and the request path to app.log.</p><p>If you are using swagger ui, don’t forget to exclude it from logging, this is because we would only want to log the actual API calls, nothing other than that.</p><h4>Endpoint for Retrieving Logs</h4><p>To make the logs accessible, we created an endpoint /logs that reads from app.log and returns the contents:</p><pre>[HttpGet(&quot;logs&quot;)]<br>public async Task&lt;IActionResult&gt; Logs()<br>{<br>    var logFilePath = Path.Combine(&quot;/app/logs&quot;, &quot;app.log&quot;);<br>    var allLogs = await System.IO.File.ReadAllTextAsync(logFilePath);<br>    return Ok(allLogs);<br>}</pre><p>Now, each request will be recorded in app.log, and you can retrieve them via the /logs endpoint. Try this out by making some API requests and then viewing the logs.</p><h4>Building and Running with Docker Compose</h4><p>Since we have made changes to our source code, we need to rebuild our colours-api image to include new changes. Let’s give it version 3.0.0. Build the API image with the following command:</p><pre>docker build --rm -t colours-api:3.0.0 .</pre><p>This command will create a new Docker image for the API, tagged as colours-api:3.0.0. You should be able to see it by running command docker images :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPK5O2eQkx-kpoXhp8DZYA.png" /></figure><h3>Step 2:</h3><h3>Modifying docker-compose.yml to Use Volumes</h3><p>To enable data persistence for our logs, we’ll add a <strong>volume</strong> to docker-compose.yml. This volume will map the logs directory inside the container to a Docker-managed volume outside it.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  api:<br>    image: modulez33/colours-api:3.0.0<br>    environment:<br>        - ASPNETCORE_ENVIRONMENT=Development<br>        - ASPNETCORE_URLS=http://+:5000<br>        - ConnectionStrings__Default=User ID=postgres;Password=123456;Server=postgres;Port=5432;Database=coloursdb;Pooling=true;<br>        - Redis__Host=redis<br>        - Redis__Port=6379<br>    volumes:<br>        - colours_api_logs_data:/app/logs <br>    ports:<br>        - &quot;5000:5000&quot;<br>        - &quot;5001:5001&quot;<br>    depends_on:<br>        - postgres<br>        - redis<br><br>  postgres:<br>    image: postgres:latest<br>    environment:<br>        POSTGRES_USER: postgres<br>        POSTGRES_PASSWORD: 123456<br>        POSTGRES_DB: coloursdb<br>    ports:<br>        - &quot;5432:5432&quot;<br><br>  redis:<br>    image: redis:latest<br>    ports:<br>        - &quot;6379:6379&quot;<br><br>volumes:<br>  colours_api_logs_data: {}</pre><p>Notice the “<em>volumes</em>” sections in our updated docker-compose file. This is the same file we created in Part-2 in order to deal with Postgres and Redis dependencies. In this Part-3, we did:</p><ul><li>Defined a volume named colours_api_logs_data and attached it to /app/logs inside the API container.</li><li>Now, anything logged to /app/logs/app.log will persist in colours_api_logs_data, even if the container is stopped or removed.</li><li>and changed Colours API image version from colours-api:2.0.0 to colours-api:3.0.0</li></ul><h4>Start the Services with Docker Compose</h4><p>Once the image is built, use Docker Compose to spin up the API along with PostgreSQL and Redis:</p><pre>docker-compose up</pre><p>This command will:</p><ul><li>Spin up three containers: the API, PostgreSQL, and Redis.</li><li>Ensure that the API only starts once PostgreSQL and Redis are ready, thanks to the depends_on directive.</li></ul><p>You should see something like following in your console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KattzU2AxerhjLl5M1K0ZQ.png" /><figcaption>Containsers started</figcaption></figure><p>You can now access the API at <a href="http://localhost:5000/">http://localhost:5000</a></p><h3>Step 3:</h3><h3>Testing Persistent Logs with Volumes</h3><p>Let’s see this in action by testing the persistence of logs across container restarts.</p><ol><li><strong>Generate some logs</strong>: Make a few API calls, such as GET /colours, POST /colours .</li><li><strong>Check the logs</strong>: After calling above endpoints, our requests must have been logged. Lets call GET /logs endpoint to confirm. It gives following response:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*ZDpGtekuDtsuR6GpMne3fQ.png" /></figure><ol><li><strong>Remove the containers</strong>: Run docker-compose down to remove the containers.</li><li><strong>Rebuild the containers</strong>: Now, run docker-compose up -d again to recreate the containers.</li><li><strong>Check the logs</strong>: Call GET /logs again. You should see the logs from your previous session!</li></ol><p>By persisting data in volumes, Docker ensures that critical data is retained even when the container lifecycle changes. This is essential for logs, databases, and any data that requires long-term storage.</p><h4>Source Code:</h4><p><a href="https://github.com/zeecorleone/colours.API/">GitHub - zeecorleone/Colours.API: API allowing user to create, update, get colour codes using PostgreSQL for persistence, and Redis for Caching</a></p><h3>Wrapping Up and What’s Next</h3><p>In this third part of the Docker series, we explored Docker volumes and their ability to preserve data across container lifecycles. In this simple example, we enabled persistent logging in our .NET 8.0 API using volumes. Now, you can confidently maintain important data across container restarts.</p><p>Stay tuned for <em>Part 4</em>, where we’ll dive into running the API over HTTPS inside the Docker container, and securing your application in a production-like environment.</p><p>Feel free to check out <a href="https://medium.com/@zeeshan.mustafa91/dockerize-net-8-0-web-api-cbb4b8426fdb"><em>Part 1</em> here</a> and <a href="https://medium.com/@zeeshan.mustafa91/docker-multi-container-setup-for-net-8-0-web-api-with-postgresql-and-redis-5147f1-5147f1f269cd"><em>Part 2 </em>here</a> if you missed it, and keep an eye out for the next part of this Docker series!</p><p>Happy coding : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5880971b17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Part 2: Multi-Container Setup for .NET 8.0 Web API with PostgreSQL and Redis]]></title>
            <link>https://medium.com/@zeeshan.mustafa91/docker-multi-container-setup-for-net-8-0-web-api-with-postgresql-and-redis-5147f1-5147f1f269cd?source=rss-f4f915f35f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/5147f1f269cd</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dotnet-8]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <dc:creator><![CDATA[Zeeshan Mustafa]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 16:32:44 GMT</pubDate>
            <atom:updated>2024-11-02T16:32:44.196Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Part 2: Multi-Container Setup for .NET 8.0 Web API with PostgreSQL and Redis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*RoBSl6gyHc89getK2ARe2w.png" /><figcaption>Docker + Compose + .NET = ❤</figcaption></figure><p>In this article (<em>Part 2</em> of the series), we’ll extend the Colours API, introduce PostgreSQL as the database for persistent storage, and use Redis for caching. Finally, we’ll spin up everything using Docker Compose, which simplifies managing multi-container environments.</p><p>In <em>Part 1</em> of this series, we covered the basics of containerizing a .NET 8.0 Web API using Docker. If you missed that, I highly recommend checking it out (link below). We laid the foundation by creating a simple Web API and running it inside a Docker container. As promised, this article will build on that by exploring more advanced scenarios, such as dealing with container dependencies in a multi-container setup.</p><p><a href="https://medium.com/@zeeshan.mustafa91/dockerize-net-8-0-web-api-cbb4b8426fdb">Docker Part 1: Containerize .NET 8.0 Web API</a></p><h3>Objectives:</h3><ol><li><strong>Switch from in-memory storage to PostgreSQL</strong> for persistent data storage.</li><li><strong>Add Redis caching</strong> to improve performance for read-heavy operations.</li><li><strong>Leverage Docker Compose</strong> to manage and run multiple containers (API, PostgreSQL, Redis).</li></ol><h3>Extending the Colours API</h3><p>Previously, the API used in-memory storage. Now, we’ve added PostgreSQL as the data store and Redis for caching operations. And we’ll use docker images of PostgreSQL and Redis for this.<br>Below is a snippet of the updated ColoursController that uses Redis for caching and PostgreSQL as the database.</p><pre>        [HttpPost]<br>        public async Task&lt;IActionResult&gt; Post(ColourModel model)<br>        {<br>            var newColour = new Models.Colour()<br>            {<br>                Name = model.Name,<br>                Code = model.Code,<br>                Description = model.Description,<br>            };<br><br>            var addedObj = await _appDbContext.Colours.AddAsync(newColour);<br>            await _appDbContext.SaveChangesAsync();<br><br>            var expireyTime = DateTimeOffset.Now.AddSeconds(60);<br>            _cacheService.SetData&lt;Colour&gt;($&quot;colour{newColour.Id}&quot;, newColour, expireyTime);<br><br>            return CreatedAtAction(nameof(Get), new { id = newColour.Id }, model);<br>        }<br><br>        [HttpGet(&quot;{id:int}&quot;)]<br>        public async Task&lt;IActionResult&gt; Get(int id)<br>        {<br><br>            var cacheData = _cacheService.GetData&lt;Colour&gt;($&quot;colour{id}&quot;);<br>            if (cacheData is not null)<br>                return Ok(GetColourModel(cacheData));<br><br>            var colour = _appDbContext.Colours.FirstOrDefault(c =&gt; c.Id == id);<br>            if (colour is null)<br>                return NotFound($&quot;Colour with Id {id} does not exist&quot;);<br><br>            var expireyTime = DateTimeOffset.Now.AddSeconds(60);<br>            _cacheService.SetData&lt;Colour&gt;($&quot;colour{colour.Id}&quot;, colour, expireyTime);<br><br>            return Ok(GetColourModel(colour));<br>        }</pre><blockquote>In order to stick to the topic, which is ‘docker containers’, I have mentioned only two methods above, just get an idea about the changes introduced. If you are interested in all changes, the link to the complete source code is linked below:</blockquote><p><a href="https://github.com/zeecorleone/Colours.API">GitHub - zeecorleone/Colours.API: Demo API allowing user to create, update, get colour codes in-memory</a></p><p>As you can see, we’ve implemented caching using Redis for the GET requests, ensuring better performance by reducing unnecessary database calls. Data is stored in Redis for 60 seconds before expiring. Similarly, when adding new data or deleting entries, Redis cache is updated accordingly.</p><p>For a full view of the API code, visit the GitHub repository linked above.</p><h3>Using Docker Compose for Multi-Container Setup</h3><p>Managing multiple containers can be cumbersome, which is where Docker Compose shines. We’ll use it to spin up the API, PostgreSQL, and Redis containers in one go. Here’s the docker-compose.yml file that orchestrates everything:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  api:<br>    image: colours-api:2.0.0<br>    environment:<br>        - ASPNETCORE_ENVIRONMENT=Development<br>        - ASPNETCORE_URLS=http://+:5000<br>        - ConnectionStrings__Default=User ID=postgres;Password=123456;Server=postgres;Port=5432;Database=coloursdb;Pooling=true;<br>        - Redis__Host=redis<br>        - Redis__Port=6379<br>    ports:<br>        - &quot;5000:5000&quot;<br>        - &quot;5001:5001&quot;<br>    depends_on:<br>        - postgres<br>        - redis<br><br>  postgres:<br>    image: postgres:latest<br>    environment:<br>        POSTGRES_USER: postgres<br>        POSTGRES_PASSWORD: 123456<br>        POSTGRES_DB: coloursdb<br>    ports:<br>        - &quot;5432:5432&quot;<br><br>  redis:<br>    image: redis:latest<br>    ports:<br>        - &quot;6379:6379&quot;</pre><h3>Breaking Down the docker-compose.yml</h3><p>Each service defined in the docker-compose.yml file represents a container that will be started. The services are defined as top-level keys, such as api, postgres, and redis in the example. Docker Compose automatically creates a network for your services. Each service in the docker-compose.yml file can communicate with others via the service name as the hostname instead of localhost.</p><ul><li><strong>API Service</strong>:<br>Our API image is colours-api:2.0.0. It exposes ports 5000 and 5001. The environment variables define PostgreSQL connection strings and Redis configuration.</li><li><strong>PostgreSQL Service</strong>:<br>The database service is using the official PostgreSQL image. We’ve set up the username, password, and database name in the environment section.</li><li><strong>Redis Service</strong>:<br>We use the Redis image to manage our caching layer. The API will communicate with Redis on port 6379.</li><li>environment: Sets the environment variables for the container.</li><li>ports: Maps the port from the container to the host.</li><li>depends_on: Ensurs that the api service starts only after the postgres and redis services have been started.</li></ul><h3>Building and Running with Docker Compose</h3><h4>Step 1: Build the API Image</h4><p>Make sure you’ve built the API image with the following command:<br><em>(if you have already done this following Part-1 of the series, you can skip this)</em></p><pre>docker build --rm -t colours-api:2.0.0 .</pre><p>This command will create a new Docker image for the API, tagged as colours-api:2.0.0. You should be able to see it by running command docker images :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpEvx4ruPwGZOuDQfzXlJQ.png" /></figure><h4>Step 2: Start the Services with Docker Compose</h4><p>Once the image is built, use Docker Compose to spin up the API along with PostgreSQL and Redis:</p><pre>docker-compose up</pre><p>This command will:</p><ul><li>Spin up three containers: the API, PostgreSQL, and Redis.</li><li>Ensure that the API only starts once PostgreSQL and Redis are ready, thanks to the depends_on directive.</li></ul><p>You should see something like following in your console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KattzU2AxerhjLl5M1K0ZQ.png" /><figcaption>Containsers started</figcaption></figure><p>You can now access the API at http://localhost:5000, and it will be backed by PostgreSQL for persistent data storage and Redis for caching.</p><h3>Verifying the Setup</h3><p>After everything is up and running, you can interact with the API using tools like Postman or curl. For example, you can add a new colour:</p><pre>curl -X POST http://localhost:5000/colours -H &quot;Content-Type: application/json&quot; -d &quot;{\&quot;name\&quot;:\&quot;Blue\&quot;,\&quot;code\&quot;:\&quot;#0000FF\&quot;,\&quot;description\&quot;:\&quot;A nice shade of blue.\&quot;}&quot;</pre><p>Or, fetch the list of colours (from Redis cache if available):</p><pre>curl http://localhost:5000/colours</pre><p><strong>Note: You might encounter an exception:</strong><br>Npgsql.PostgresException (0x80004005): 42P01: relation “Colours” does not exist”</p><p>This happens because the migrations has not been run within the container, and hence the db doesn’t contain any table definition yet. You can correct this by added following lines in your program.cs</p><pre>//appy migrations automatically:<br>using (var scope = app.Services.CreateScope())<br>{<br>    var services = scope.ServiceProvider;<br>    try<br>    {<br>        var context = services.GetRequiredService&lt;AppDbContext&gt;();<br>        context.Database.Migrate();<br>    }<br>    catch(Exception ex)<br>    {<br>        var logger = services.GetRequiredService&lt;ILogger&lt;Program&gt;&gt;();<br>        logger.LogError(ex, &quot;Error occurred while applying migrations.&quot;);<br>    }<br>}</pre><p>This will require re building the image. This gives us chance to practice what we just learnt above and in Part-1 : )<br>Build the new image, let’s say colours-api:3.0.0 and update your docker-compose file to use this one instead.</p><h3>What’s Next?</h3><p>In this article, we focused on adding PostgreSQL and Redis support to our API and managing these containers using Docker Compose. This is just one step toward more advanced Docker topics.</p><p>Stay tuned for <em>Part 3</em>, where we’ll dive into running the API over HTTPS inside the Docker container, dealing with volumes, and securing your application in a production-like environment.</p><p>Feel free to check out <a href="https://medium.com/@zeeshan.mustafa91/dockerize-net-8-0-web-api-cbb4b8426fdb"><em>Part 1</em> here</a> if you missed it, and keep an eye out for the next part of this Docker series!</p><p>Happy coding : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5147f1f269cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Part 1: Containerize .NET 8.0 Web API]]></title>
            <link>https://medium.com/@zeeshan.mustafa91/dockerize-net-8-0-web-api-cbb4b8426fdb?source=rss-f4f915f35f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbb4b8426fdb</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Zeeshan Mustafa]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 13:43:10 GMT</pubDate>
            <atom:updated>2024-09-09T13:43:10.554Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Part 1: Containerize .NET 8.0 Web API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7DO9NTcX0JfvWrQlXPDnQ.png" /><figcaption>.NET + Docker = ❤</figcaption></figure><p>Docker has become an essential tool for developers, especially when it comes to building and deploying applications consistently across different environments. In this tutorial, we will walk you through the process of dockerizing a simple .NET 8.0 Web API. This article is aimed at beginners who are new to Docker, particularly those working in the .NET ecosystem. By the end of this guide, you’ll have your .NET Web API running inside a Docker container.</p><p>Just as the title says, this is the “Part-1” of a series where we’ll build on this foundation, covering more advanced scenarios like running this API over HTTPS inside Docker container, dealing with other container dependencies (multi container) within your application, etc.</p><h3>Prerequisites</h3><p>Before we dive in, ensure you have the following installed on your machine:</p><ol><li><strong>.NET SDK 8.0</strong> — <a href="https://dotnet.microsoft.com/en-us/download/dotnet/8.0">Download Here</a></li><li><strong>Docker Desktop</strong> — <a href="https://www.docker.com/products/docker-desktop/">Download Here</a></li></ol><h3>Step 1: Understanding the Colours.API</h3><p>For this tutorial, we’ll use a simple .NET 8.0 Web API named Colours.API. This API allows you to manage a list of colors through basic CRUD operations (Create, Read, Update, Delete).</p><p>The full controller code for the API can be found in this <a href="https://gist.github.com/zeecorleone/0ca7770852e22010189fa3eba7e4ebcf">GitHub Gist</a>.<br>When run locally, this is how its endpoints look like in Swagger:</p><figure><img alt="Colours.API running locally" src="https://cdn-images-1.medium.com/max/1024/1*OR8xdfC_KMqKuyvQx-wa5g.png" /></figure><h3>Step 2: Writing the Dockerfile</h3><p>A Dockerfile is a script that contains a series of commands that are executed to assemble a Docker image. <br>Create a new file at root level of your solution, and name it Dockerfile without any extension (this is important).</p><p>This is how it should look like in file explorer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*t_VUuA5YwVOfjYjKot7XyQ.png" /></figure><p>Below is the content of the Dockerfile used to containerize our Colours.API:</p><pre># Build Stage<br>FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build<br>WORKDIR /source<br>COPY . .<br>RUN dotnet restore &quot;./Colours.API/Colours.API.csproj&quot; --disable-parallel<br>RUN dotnet publish &quot;./Colours.API/Colours.API.csproj&quot; -c release -o /app --no-restore<br><br># Serve Stage<br>FROM mcr.microsoft.com/dotnet/aspnet:8.0<br>WORKDIR /app<br>COPY --from=build /app ./<br><br>EXPOSE 5000<br>EXPOSE 5001<br><br>ENTRYPOINT [&quot;dotnet&quot;, &quot;Colours.API.dll&quot;]</pre><h4>Breaking Down the Dockerfile</h4><ul><li><strong>FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build</strong>:<br>This line specifies the base image for the build stage, which is the .NET SDK 8.0. It contains all the necessary tools to build and publish our .NET application.</li><li><strong>WORKDIR /source</strong>:<br>Sets the working directory inside the container to /source.</li><li><strong>COPY . .</strong>:<br>Copies all files from the current directory (on your machine) to the /source directory inside the container.</li><li><strong>RUN dotnet restore &amp; dotnet publish</strong>:<br>These commands restore the dependencies and publish the application to the /app directory.</li><li><strong>FROM mcr.microsoft.com/dotnet/aspnet:8.0</strong>:<br>This line defines the base image for the serve stage, which is optimized for running ASP.NET Core applications.</li><li><strong>WORKDIR /app</strong>:<br>Sets the working directory inside the container to /app.</li><li><strong>COPY — from=build /app ./</strong>:<br>Copies the published output from the build stage into the serve stage.</li><li><strong>EXPOSE 5000 &amp; 5001</strong>:<br>Exposes ports 5000 and 5001, which the API will listen on.</li><li><strong>ENTRYPOINT [“dotnet”, “Colours.API.dll”]</strong>:<br>Specifies the command to run the application inside the container.</li></ul><h3>Step 3: Building the Docker Image</h3><p>Once you have your Dockerfile ready, the next step is to build the Docker image. Navigate to the directory containing your Dockerfile and run the following command:</p><pre>docker build --rm -t colours-api:1.0.0 .</pre><p><strong>Important:</strong> Don’t miss the dot at the end.</p><p>This command will:</p><ul><li><strong>Build</strong> the Docker image with the tag colours-api:1.0.0.</li><li><strong>— rm</strong> ensures that intermediate containers created during the build process are removed automatically.</li><li><strong>. (dot) </strong>specifies that the Dockerfile is in the current directory.</li></ul><h3>Step 4: Running the Docker Container</h3><p>After successfully building your Docker image, you can run it using the following command:</p><pre>docker run --rm -p 5000:5000 -p 5001:5001 -e ASPNETCORE_ENVIRONMENT=Development -e ASPNETCORE_URLS=&quot;http://+:5000&quot; colours-api:1.0.0</pre><p>Here’s what each part of the command does:</p><ul><li><strong>— rm</strong>: Automatically removes the container when it exits.</li><li><strong>-p 5000:5000 -p 5001:5001</strong>: Maps the container’s ports 5000 and 5001 to your local machine’s ports 5000 and 5001.</li><li><strong>-e ASPNETCORE_ENVIRONMENT=Development</strong>: Sets the environment variable inside the container to Development.</li><li><strong>-e ASPNETCORE_URLS=”http://+:5000&quot;</strong>: Configures the application to listen on port 5000.</li><li><strong>colours-api:1.0.0</strong>: Specifies the image to run.</li></ul><p>As soon as you run this comment, you should be able to see something like following on the console. If not, then something might be wrong, and you should be able to see the error message or exception trace instead.</p><pre>info: Microsoft.Hosting.Lifetime[14]<br>      Now listening on: http://[::]:5000<br>info: Microsoft.Hosting.Lifetime[0]<br>      Application started. Press Ctrl+C to shut down.<br>info: Microsoft.Hosting.Lifetime[0]<br>      Hosting environment: Development<br>info: Microsoft.Hosting.Lifetime[0]<br>      Content root path: /app</pre><h3>Step 5: Accessing the API</h3><p>With the container running, you can now access the Colours API by navigating to http://localhost:5000/Colours. This should return a list of colors if any exist in your database. You can use tools like Postman or cURL to interact with the API and test its various endpoints. Or you can use swagger url <a href="http://localhost:5000/swagger/index.html">http://localhost:5000/swagger/index.html</a> it should show like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*iF0Isz2VEmOtRDdYvWQGNw.png" /></figure><h3>Conclusion</h3><p>Congratulations! You’ve successfully dockerized your first .NET 8.0 Web API. This tutorial provided you with the basics of Docker and how to containerize a .NET application. In the next part of this series, we’ll explore how to deal with multi-containers when this API depends on another container, and how to run this API over HTTPS inside Docker container, along with other advanced scenarios.</p><p>Stay tuned for Part 2!</p><p>Happy Coding : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbb4b8426fdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use HttpClient Right Way!]]></title>
            <link>https://medium.com/@zeeshan.mustafa91/use-httpclientfactory-right-way-d3fb877913c0?source=rss-f4f915f35f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3fb877913c0</guid>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[dotnet-8]]></category>
            <dc:creator><![CDATA[Zeeshan Mustafa]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 15:49:18 GMT</pubDate>
            <atom:updated>2024-09-01T13:01:15.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bRz5uMEt_RQxabuktyLRg.png" /></figure><p>Traditionally, making HTTP calls in .NET applications involved using the HttpClient class directly. This often led to issues with managing the lifecycle of the HttpClient instances, resulting in socket exhaustion and performance problems.</p><p>Here’s an example of the old way of making an HTTP call:</p><pre>public async Task&lt;string&gt; GetWeatherDataAsync(string city, string apiKey)<br>{<br>    using (var httpClient = new HttpClient())<br>    {<br>        var url = $&quot;https://api.openweathermap.org/data/2.5/weather?q={city}&amp;appid={apiKey}&quot;;<br>        var response = await httpClient.GetAsync(url);<br>        <br>        if (response.IsSuccessStatusCode)<br>        {<br>            return await response.Content.ReadAsStringAsync();<br>        }<br><br>        return null;<br>    }<br>}</pre><p>When CreateClient is called, a new instance of HttpClient is created.</p><h4>Why Use IHttpClientFactory?</h4><p>The IHttpClientFactory was introduced in .NET Core 2.1 to address several issues with the direct use of HttpClient. It provides a centralized way to configure and create HttpClient instances, ensuring proper resource management and improved performance.</p><h4>Problems Solved by IHttpClientFactory</h4><ol><li><strong>Socket Exhaustion</strong>: Improper disposal of HttpClient instances can lead to socket exhaustion. IHttpClientFactory manages the lifetimes of HttpClientMessageHandler instances to prevent this.</li><li><strong>Centralized Configuration</strong>: It allows centralized configuration of HttpClient instances, making it easier to apply consistent settings.</li><li><strong>Named and Typed Clients</strong>: Provides a way to create named and typed clients, allowing specific configurations for different uses.</li></ol><h3>3 Ways to Use IHttpClientFactory</h3><p>There are three possible ways you can use IHttpClientFactory in your .NET project. Let’s see all three in action, one by one.</p><h4>#1: Simply inject IHttpClientFactory and use it:</h4><p>First, register the IHttpClientFactory in the Startup.cs:</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddHttpClient();<br>}</pre><p>Now, modify the method to use IHttpClientFactory:</p><pre>public class WeatherService<br>{<br>    private readonly IHttpClientFactory _httpClientFactory;<br><br>    public WeatherService(IHttpClientFactory httpClientFactory)<br>    {<br>        _httpClientFactory = httpClientFactory;<br>    }<br><br>    public async Task&lt;string&gt; GetWeatherDataAsync(string city, string apiKey)<br>    {<br>        var httpClient = _httpClientFactory.CreateClient();<br>        var url = $&quot;https://api.openweathermap.org/data/2.5/weather?q={city}&amp;appid={apiKey}&quot;;<br>        var response = await httpClient.GetAsync(url);<br><br>        if (response.IsSuccessStatusCode)<br>        {<br>            return await response.Content.ReadAsStringAsync();<br>        }<br><br>        return null;<br>    }<br>}</pre><h4>#2: IHttpClientFactory using named clients:</h4><p>Named clients allow you to configure HttpClient instances with specific settings for different purposes.</p><p>Registering Named Clients:</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddHttpClient(&quot;WeatherClient&quot;, client =&gt;<br>    {<br>        client.BaseAddress = new Uri(&quot;https://api.openweathermap.org/&quot;);<br>        client.DefaultRequestHeaders.Add(&quot;Accept&quot;, &quot;application/json&quot;);<br>    });<br>}</pre><p>Now modify the WeatherService to use the named client instead:</p><pre>public class WeatherService<br>{<br>    private readonly IHttpClientFactory _httpClientFactory;<br><br>    public WeatherService(IHttpClientFactory httpClientFactory)<br>    {<br>        _httpClientFactory = httpClientFactory;<br>    }<br><br>    public async Task&lt;string&gt; GetWeatherDataAsync(string city, string apiKey)<br>    {<br>        var httpClient = _httpClientFactory.CreateClient(&quot;WeatherClient&quot;);<br>        var url = $&quot;data/2.5/weather?q={city}&amp;appid={apiKey}&quot;;<br>        var response = await httpClient.GetAsync(url);<br><br>        if (response.IsSuccessStatusCode)<br>        {<br>            return await response.Content.ReadAsStringAsync();<br>        }<br><br>        return null;<br>    }<br>}</pre><p>Notice that we haven’t specify the hostname inside GetWeatherDataAsync method this time, because we have already set the base address for this client when registering it in DI.</p><h4>#3: IHttpClientFactory using Typed clients:</h4><p>Typed clients provide a way to encapsulate HTTP logic into a reusable class. Let’s create one and name it WeatherCleint</p><pre>public class WeatherCleint<br>{<br>     private readonly HttpClient _httpClient;<br><br>     public WeatherCleint(HttpClient httpClient)<br>     {<br>        _httpClient = httpClient;<br>     }<br><br>     public async Task&lt;string&gt; GetWeatherDataAsync(string city, string apiKey)<br>     {<br>          var url = $&quot;data/2.5/weather?q={city}&amp;appid={apiKey}&quot;;<br>          var response = await _httpClient.GetAsync(url);<br>          if (response.IsSuccessStatusCode)<br>          {<br>              return await response.Content.ReadAsStringAsync();<br>          }<br>          return null;<br>     }<br>}</pre><p>Now, let’s register our typed client in DI:</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddHttpClient&lt;WeatherClient&gt;(client =&gt;<br>    {<br>        client.BaseAddress = new Uri(&quot;https://api.openweathermap.org/&quot;);<br>        client.DefaultRequestHeaders.Add(&quot;Accept&quot;, &quot;application/json&quot;);<br>    });<br>}</pre><p>The AddHttpClientmethod registers the WeatherClient as transientservice.</p><p>Now modify the WeatherService to use the named client instead:</p><pre>public class WeatherService<br>{<br>    private readonly WeatherClient _weatherClient;<br><br>    public WeatherService(WeatherClient weatherClient)<br>    {<br>        _weatherClient = weatherClient;<br>    }<br><br>    public async Task&lt;string&gt; GetWeatherDataAsync(string city, string apiKey)<br>    {<br>        return await _weatherClient.GetWeatherDataAsync(city, apiKey);<br>    }<br>}</pre><h4>Warning:</h4><p>Avoid injecting typed clients inside singleton services. The HttpClient is expected to be short lived. If typed client is captured in singleton, it may not get get disposed appropriately, hence defeating the purpose of IHttpClientFactory.</p><h3>Closing</h3><p>Using IHttpClientFactory in .NET is a powerful way to manage HTTP client lifetimes, avoid common pitfalls like socket exhaustion, and apply centralized configuration. Whether you use the default client, named clients, or typed clients, IHttpClientFactory provides flexibility and improved performance for your applications.</p><p>I hope this tutorial has helped you gain a understanding of using IHttpClientFacotry and different ways to implement it. Stay tuned for more articles as we continue to explore the powerful features of .NET 8.0 and beyond.</p><p>Happy coding!</p><p>Source Code: <a href="https://github.com/zeecorleone/OpenWeatherAPI">https://github.com/zeecorleone/OpenWeatherAPI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3fb877913c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC with JSON Transcoding for HTTP Support in NET 8.0]]></title>
            <link>https://medium.com/@zeeshan.mustafa91/grpc-with-json-transcoding-for-http-support-dotnet8-f2213bcc579a?source=rss-f4f915f35f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2213bcc579a</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[json-transcoding]]></category>
            <dc:creator><![CDATA[Zeeshan Mustafa]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 09:15:29 GMT</pubDate>
            <atom:updated>2024-06-11T09:15:29.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*sDcm3ay4wtlIVdPWDYQ_Ww.png" /><figcaption>Json Transcoding — gRPC</figcaption></figure><p>In our <a href="https://medium.com/@zeeshan.mustafa91/gprc-with-net8-a-beginners-guide-b031076d2e2b">previous article</a>, we learned that gRPC is a powerful, lightweight, and efficient framework for communication between distributed systems. Its use of Protocol Buffers and HTTP/2 allows for fast, reliable, and type-safe communication, making it an excellent choice for modern microservices architectures.</p><blockquote>Note: If you are new to gRPC services, I recommend checking out my previous article, “<a href="https://medium.com/@zeeshan.mustafa91/gprc-with-net8-a-beginners-guide-b031076d2e2b">Unlocking the Power of gRPC with .NET 8.0: A Beginner’s Guide,</a>” where I explain the basic workings of gRPC. This article builds upon that foundation, so starting there will help you better understand the concepts discussed here. The link is given below.</blockquote><p><a href="https://medium.com/@zeeshan.mustafa91/gprc-with-net8-a-beginners-guide-b031076d2e2b">Unlocking the Power of gPRC with .NET 8.0: A Beginner’s Guide</a></p><h3>Why?</h3><p>Why Enable gRPC over HTTP?</p><p>You might be wondering why we need to expose gRPC service endpoints over HTTP, especially since gRPC is often chosen to avoid the overhead associated with HTTP. There are several compelling use cases for this approach.</p><p>Common one being, it allows you to use the same service for internal communication among your applications (or microservices, etc.) while also enabling your external applications to leverage these services through http without requiring significant changes.</p><p>Here are some of the other reasons to enable HTTP/JSON access:</p><ol><li>Interoperability: Allowing HTTP/JSON access facilitates communication with clients that do not support gRPC, such as web browsers and legacy systems.</li><li>Ease of Use: JSON is a widely-used data interchange format that is easily readable by both humans and machines, simplifying development and debugging processes.</li><li>Flexibility: Supporting HTTP/JSON requests can simplify integration with existing RESTful APIs, enabling a smoother transition and coexistence of gRPC and REST services.</li></ol><p>In this tutorial, we’ll extend our existing gRPC example to support JSON Transcoding, allowing our gRPC service to be called over the HTTP protocol. By the end of this article, you’ll understand how to configure your gRPC service to handle both gRPC and HTTP/JSON requests seamlessly. Let’s dive in and enhance our gRPC service with the versatility of HTTP support.</p><h3>Json Transcoding:</h3><p>We’ll use <a href="https://cloud.google.com/endpoints/docs/grpc/transcoding"><strong><em>Json Transcoding</em></strong></a><strong><em> </em></strong>for enabling our gRPC service to be accssible over http.</p><p>gRPC JSON transcoding is an extension for ASP.NET Core that creates RESTful JSON APIs for gRPC services. Once configured, transcoding allows apps to call gRPC services with familiar HTTP concepts:</p><ul><li>HTTP verbs</li><li>URL parameter binding</li><li>JSON requests/responses</li></ul><h3>Setup:</h3><ol><li>In our ‘<strong>ToDo</strong>’ gRPC service application we created in our <a href="https://medium.com/@zeeshan.mustafa91/gprc-with-net8-a-beginners-guide-b031076d2e2b">previous article</a>, add the following NuGet package</li></ol><pre>Install-Package Microsoft.AspNetCore.Grpc.JsonTranscoding</pre><p>2. In our “<em>program.cs</em>” class, we already have called “<em>AddGrpc()</em>”. Just add “<strong><em>AddJsonTranscoding()</em></strong>” which is available after adding the above NuGet package. It should look like:</p><pre>builder.Services.AddGrpc().AddJsonTranscoding();</pre><p>3. In our .csproj file, we need to “<strong>&lt;IncludeHttpRuleProtos&gt;</strong>” tag inside “<em>PropertyGroup</em>”, and set its value to “true”. It should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*mj3bISgutbU5zLDOrVJcPw.png" /></figure><p>4. If you are using <strong>.NET =&gt; 8.0</strong>, then just skip this step.</p><p>If you are using <strong>.NET &lt; 8.0</strong>, you need to add following two files in the solution under “/<strong>google/api/</strong>” path.<br>- http.proto<br>- annotations.proto</p><p>Copy the content for <strong>“http.proto”</strong> from <a href="https://github.com/dotnet/aspnetcore/blob/main/src/Grpc/JsonTranscoding/test/testassets/Sandbox/google/api/http.proto"><strong>HERE</strong></a>.<br>Similarly, copy the content for <strong>“annotations.proto”</strong> from <a href="https://github.com/dotnet/aspnetcore/blob/main/src/Grpc/JsonTranscoding/test/testassets/Sandbox/google/api/annotations.proto"><strong>HERE</strong></a></p><p>The heirarchy should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*zvUUiyVW0bHKTcK3iVptcw.png" /></figure><p>5. Now we need to annotate our “<strong>todo.proto</strong>” file with HTTP verbs. (we created this file in our previous article <a href="https://medium.com/@zeeshan.mustafa91/gprc-with-net8-a-beginners-guide-b031076d2e2b">here</a></p><pre>syntax = &quot;proto3&quot;;<br><br>option csharp_namespace = &quot;TodoGrpc&quot;;<br><br>import &quot;google/api/annotations.proto&quot;; <br><br>package todoit;<br><br>service ToDoIt {<br><br>    //Create<br>    rpc CreateToDo(CreateToDoRequest) returns (CreateToDoResponse) {<br>         option (google.api.http) = { <br>             post: &quot;/v1/todo&quot;,<br>             body: &quot;*&quot;<br>         };<br>    }<br><br>    //GetById<br>    rpc GetById(ReadToDoRequest) returns (ReadToDoResponse) {<br>        option (google.api.http) = { <br>              get: &quot;/v1/todo/{id}&quot;<br>          };<br>    }<br><br>}<br><br>message CreateToDoRequest {<br>    string title = 1;<br>    string description = 2;<br>}<br><br>message CreateToDoResponse {<br>    int32 id = 1;<br>}<br><br>message ReadToDoRequest {<br>    int32 id = 1;<br>}<br><br>message ReadToDoResponse {<br>    int32 id = 1;<br>    string title = 2;<br>    string description = 3;<br>}</pre><p>What we changed in our “<strong>todo.proto</strong>” file above:</p><ul><li>Imported <strong>annotations.proto </strong>by adding line <em>import “google/api/annotations.proto”</em></li><li>Annotated “<strong><em>CreateToDo</em></strong>” rpc method by adding following:</li></ul><pre>option (google.api.http) = {<br>    post: &quot;/v1/todo&quot;,<br>    body: &quot;*&quot;<br> };</pre><ul><li>Similarly, annotated “<strong><em>GetById</em></strong>” rpc method by adding following:</li></ul><pre>option (google.api.http) = {<br>     get: &quot;/v1/todo/{id}&quot;<br>  };</pre><p>And…</p><p>That’s it. This should now allow our gRPC service methods to be called through rest clients. Let’s see this in action.</p><p>I called “<strong><em>CreateToDo</em></strong>” endpoint over http using Postman and it was successful:</p><figure><img alt="Calling http annotated gRPC endpoint over HTTP using Postman" src="https://cdn-images-1.medium.com/max/1024/1*tjCcGgSGGtZkyC9H0N8Rpg.png" /><figcaption>Calling http annotated gRPC endpoint over http using Postman</figcaption></figure><h3>Closing:</h3><p>In this article, we’ve extended our understanding of gRPC by implementing JSON Transcoding to allow our gRPC service to be accessed over the HTTP protocol. This enhancement provides greater flexibility, interoperability, and ease of use, enabling our services to communicate seamlessly with a wider range of clients.</p><p>I hope this tutorial has helped you gain a deeper understanding of gRPC and its capabilities. Stay tuned for more articles as we continue to explore the powerful features of .NET 8.0 and beyond.</p><p>Next: We’ll try to protect our gRPC service, so only authorized users can consume it.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2213bcc579a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of gPRC with .NET 8.0: A Beginner’s Guide]]></title>
            <link>https://medium.com/@zeeshan.mustafa91/gprc-with-net8-a-beginners-guide-b031076d2e2b?source=rss-f4f915f35f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/b031076d2e2b</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[dotnet-8]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Zeeshan Mustafa]]></dc:creator>
            <pubDate>Sun, 19 May 2024 04:52:44 GMT</pubDate>
            <atom:updated>2024-05-24T15:18:22.466Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking the Power of gPRC with .NET 8.0: A Beginner’s Guide</h3><figure><img alt="gRPC using .NET 8" src="https://cdn-images-1.medium.com/max/805/1*uzjt4n3MpurZPvTEYaDOyg.png" /><figcaption>gRPC using .NET 8</figcaption></figure><p>In today’s world of software development and modern distributed systems, efficient communication between services is crucial. Enter <a href="https://grpc.io/">gRPC</a>: a high-performance framework developed by Google, leveraging HTTP/2 and <a href="https://protobuf.dev/">Protocol Buffers </a>for lightweight and efficient communication. This is achieved through its utilization of binary serialization using protobuf, leading to smaller message sizes as compared to traditional formats like JSON or XML.</p><p>gRPC solves common API challenges like over-fetching and under-fetching, offering a strongly-typed contract and built-in support for bidirectional streaming. <a href="https://grpc.io/blog/grpc-on-dotnetcore/">With native support in .NET Core 3.0</a>, it’s now easier than ever to integrate gRPC into your applications.</p><p>In this article, we’ll dive into the practical aspects of using gRPC with <strong>.NET 8.0</strong>. We’ll start with a brief overview, then move swiftly to creating and consuming gRPC services in C#. Finally, we’ll showcase a real-world example to demonstrate gRPC in action.</p><p>Ready to see how gRPC can supercharge your .NET application’s communication? Let’s dive into the code!</p><p>In our example, we’ll develop a simple ‘todo’ gRPC service and we’ll implement two methods <em>Create</em> and <em>GetById, </em>as our more focus will be the gRPC itself.</p><h3><strong>Create gRPC Service:</strong></h3><p>From VS Code terminal, run command:</p><pre>dotnet new grpc -o GrpcGreeter<br>code -r GrpcGreeter</pre><p>Or you can choose gRPC template when creating new project in <strong>Visual Studio</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*k226ntUNRooSOMeEQmKZ8Q.png" /></figure><p>Let’s examine the newly created project.</p><p>Inside “program.cs”, you should see:</p><pre>builder.Services.AddGrpc();</pre><p>This is an extension method provided by “Grpc.AspNetCore” NuGet package, and it is used to register the gRPC services with the DI container. When we call “.AddGrpc()” method, it configures the services required for hosting gRPC endpoints, including necessary middleware options.</p><p>Next thing to notice is “greet.proto” file inside “Protos” folder.</p><p><strong>What is .proto file?<br></strong>.proto files (short for Proto Buffers) serves as the foundation for defining the structure and <strong>contract </strong>of the gRPC service. This acts as the source of truth for both client and server, specifying the messages and RPC methods exchanged between them.</p><p>At its core, a .proto file defines the following components:</p><p>1. <strong>Message</strong>: These are the data structures used to exchange information between client and server. Messages are defined using a simple and language-neutral syntax, making them interoperable across different programming languages.</p><p>2. <strong>Services</strong>: Services define the RPC methods that can be called by the client. Each service method is associated with a request message and a response message, allowing for bi-directional communication between client and server.</p><p>Now let’s move on to creating our first .proto file, for our TodoService.</p><p>Under the “Protos” folder, add new item named “todo.proto”, and define define our Services/Methods and Messages so it looks like below:</p><pre>syntax = &quot;proto3&quot;;<br><br>option csharp_namespace = &quot;TodoGrpc&quot;;<br><br>package todoit;<br><br>service ToDoIt {<br><br>    //Create<br>    rpc CreateToDo(CreateToDoRequest) returns (CreateToDoResponse) {<br>        <br>    }<br><br>    //GetById<br>    rpc GetById(ReadToDoRequest) returns (ReadToDoResponse) {<br>        <br>    }<br><br>}<br><br>message CreateToDoRequest {<br>    string title = 1;<br>    string description = 2;<br>}<br><br>message CreateToDoResponse {<br>    int32 id = 1;<br>}<br><br><br>message ReadToDoRequest {<br>    int32 id = 1;<br>}<br><br>message ReadToDoResponse {<br>    int32 id = 1;<br>    string title = 2;<br>    string description = 3;<br>}</pre><p>The ‘proto’ syntax is pretty straight forward. We have defined “ToDoIt” service which contains RPC methods without implementation. This is just like an interface/contract.<br>And we have also defined our models, which are called “Messages” in gRPC world.</p><p>For example, the “<strong>CreateToDoRequest</strong>” message consists of two fields.<br>It is requirement to assign a unique number to each field within a message.</p><p>There are some restrictions around number ranges, reserved numbers, etc., and you can read more details about it <a href="https://protobuf.dev/programming-guides/proto3/">here</a>.</p><h3>Some Assumptions:</h3><p>In order to keep this guide “to the point”, we’ll assume that we already have:<br>1. <strong>DbContext </strong>injected in DI container and is ready to use.<br>2. We have a data model “<strong>TodoModel</strong>” with properties <strong>Id</strong>, <strong>Title </strong>and <strong>Description</strong>.<br>3. We have a Db collection named “<strong>TodoItems</strong>”, which is <strong>DbSet&lt;TodoModel&gt;.</strong></p><h3>Build:</h3><p>After defining the <em>todo.proto </em>file, let’s build the project. The .proto file is compiled using Protocol Buffers compiler (protoc). This generates code in target language (C# in our case) based on the definitions specified in the .proto file. The generated code includes classes and interfaces representing the message and services defined in the .proto file.</p><h4>Important:</h4><p>Make sure to add following line inside your “<strong>.csproj</strong>” file, so it gets compiled on build.</p><pre><br>  &lt;ItemGroup&gt;<br>      &lt;Protobuf Include=&quot;Protos\todo.proto&quot; GrpcServices=&quot;Server&quot; /&gt;<br>  &lt;/ItemGroup&gt;</pre><h3><strong>Next, let’s create our Todo Service.</strong></h3><p>Create a new class under a new folder, let’s call this folder “Services”. The class looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d28a70cf20bd7359f49cc22f9ae9c33/href">https://medium.com/media/7d28a70cf20bd7359f49cc22f9ae9c33/href</a></iframe><p>What just happend? We simply implemented the service methods defined in our .proto file as contracts.</p><p>The <strong>“ToDoIt.ToDoItBase”</strong> becomes available after “Build” step mention earlier.</p><p>And.. That’s it. Our gRPC service is ready. Let’s try to call it from a console (client) application.</p><h3>Create Client</h3><ol><li>Create a dotnet console application. Let’s name it “<strong>GrpcTodoClient</strong>”</li><li>Install following NuGet packages</li></ol><pre>Install-Package Grpc.Net.Client<br>Install-Package Google.Protobuf<br>Install-Package Grpc.Tools</pre><p>3. Create a new folder “Protos” inside console application solution, and copy “<strong>todo.proto</strong>” file from gRPC service project into this newly created folder.</p><p>4. Update the namespace to match the client application namespace, inside <strong>todo.proto </strong>file which we just copied. It so it looks like:</p><pre>option csharp_namespace = &quot;GrpcTodoClient&quot;;</pre><p>5. Add an item group with a <strong>&lt;Protobuf&gt;</strong> element which refers to the <strong>todo.proto </strong>file, just like we did in our gRPC service project.</p><pre>&lt;ItemGroup&gt;<br>  &lt;Protobuf Include=&quot;Protos\todo.proto&quot; GrpcServices=&quot;Client&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p><strong>Important:</strong> please note <strong>GrpcServices=“Client” </strong>part, unlike GrpcServices=<strong>“</strong>Server” in service project.</p><p>6. Now build the application. The “<strong>ToDoIt.ToDoItClient</strong>” types are automatically generated by the build process.</p><p>7. Create a gRPC channel and call the service:</p><pre>using System.Threading.Tasks;<br>using Grpc.Net.Client;<br><br><br>// The port number must match the port of the gRPC server.<br>using var channel = GrpcChannel.ForAddress(&quot;https://localhost:7015&quot;);<br>var client = new ToDoIt.ToDoItClient(channel);<br>CreateToDoResponse reply = await client.CreateToDo(<br>                  new CreateToDoRequest { Title = &quot;Task#1&quot;, Description = &quot;Wake up early&quot; });<br>Console.WriteLine(&quot;New Todo Id: &quot; + reply.Id);<br>Console.WriteLine(&quot;Press any key to exit...&quot;);<br>Console.ReadKey();<br><br>//Output: <br>//New Todo Id: 1</pre><p>Similarly, we can get the newly created todo item using <em>GetById </em>service method:</p><pre>ReadToDoResponse todo = await client.GetById(<br>                  new ReadToDoRequest { Id = 1 });<br>Console.WriteLine(&quot;Title: &quot; + todo.Title);<br>Console.WriteLine(&quot;Description: &quot; + todo.Description);<br><br>//Output:<br>//Title: Task#1<br>//Description: Wake up early<br></pre><h4>RPC Exceptions:</h4><p>In world of gRPC, error is handled differenlty than in traditional HTTP based APIs. While HTTP Status Codes are commongly used to communicate the outcome of a request in RESTful service, gRPC utilizes a different approach with RpcException and Status.</p><p>In order to keep this short and to the point, we’ll cover error/exception handling in gRPC in one of our future posts about gRPC, but you can read about how it works in .NET <a href="https://learn.microsoft.com/en-us/aspnet/core/grpc/error-handling?view=aspnetcore-8.0">here</a>.</p><h3>Closing:</h3><p>In this tutorial, we’ve explored the power of gRPC in .NET Core applications. From understanding its fundamentals to creating and consuming services, we’ve covered essential concepts and practical examples.</p><p>Next:<br>In next post, we’ll cover how can we expose our gRPC service to allow communication via http. In some use cases, we may need to support both, for example, one for internal comms and other for external/different comms.</p><p>I hope this tutorial has helped you understand the fundamentals of gRPC and inspired you to integrate it into your projects.</p><p>Happy coding! ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b031076d2e2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>