<?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 Kerim Emurla on Medium]]></title>
        <description><![CDATA[Stories by Kerim Emurla on Medium]]></description>
        <link>https://medium.com/@kerimemurla?source=rss-b08e1badd92b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Kerim Emurla on Medium</title>
            <link>https://medium.com/@kerimemurla?source=rss-b08e1badd92b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:16:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kerimemurla/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[Rendering razor views that contain helpers with RazorEngine]]></title>
            <link>https://medium.com/@kerimemurla/rendering-razor-views-that-contain-helpers-with-razorengine-226183543b35?source=rss-b08e1badd92b------2</link>
            <guid isPermaLink="false">https://medium.com/p/226183543b35</guid>
            <category><![CDATA[aspnet-mvc]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Kerim Emurla]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 06:44:59 GMT</pubDate>
            <atom:updated>2023-08-17T06:44:59.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Razor engine logo" src="https://cdn-images-1.medium.com/max/960/1*09q4NVPx4QX98ikwvWAitw.png" /></figure><h4>The problem</h4><p>I recently was working on a codebase that was using .NET 4.7.2, where we began porting a portion of the codebase that was sitting in MVC controllers to API controllers. A part of the code that we were porting included rendering razor views. Since the code I mentioned was sitting in MVC views, rendering razor views was done by built-in MVC mechanism.</p><p>Of course, when I started porting the code that was rendering the razor views, I no longer had access to those MVC goodies, so I basically had to rewrite how the razor views are rendered by making sure the end result stays the same.</p><p>After doing a bit of research, I decided the easiest way to emulate the same result would be by utilizing <a href="https://antaris.github.io/RazorEngine/">RazorEngine</a>.</p><p>Rendering the view with <a href="https://antaris.github.io/RazorEngine/">RazorEngine</a> was straightforward enough. All I had to was to read the view into a string variable and call RazorEngine’s RunCompile method.</p><p>After doing all that however, I got hit with the following errors:</p><pre>- error: (853, 30) The name ‘Html’ does not exist in the current context<br>- error: (871, 52) The name &#39;Json&#39; does not exist in the current context</pre><p>Checking out the template I was trying to render, I saw the template was using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.htmlhelper.raw?view=aspnet-mvc-5.2">Html.Raw</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.helpers.json.encode?view=aspnet-webpages-3.2">Json.Encode</a>.</p><h4>The solution</h4><p>Luckily, the solution to the problem I was facing was straightforward enough.</p><p>Here are the three classes that were necessary in order for RazorEngine to start compiling templates that contained <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.htmlhelper.raw?view=aspnet-mvc-5.2">Html.Raw</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.helpers.json.encode?view=aspnet-webpages-3.2">Json.Encode</a>:</p><pre>public class HtmlHelpers<br>{<br>    public IEncodedString Raw(string rawString)<br>    {<br>        return new RawString(rawString);<br>    }<br>}<br><br>public class JsonHelpers<br>{<br>    public string Encode(object value)<br>    {<br>        return Json.Encode(value);<br>    }<br>}<br><br>public abstract class HtmlSupportTemplateBase&lt;T&gt; : TemplateBase&lt;T&gt;<br>{<br>    public HtmlHelpers Html { get; set; } = new HtmlHelpers();<br><br>    public JsonHelpers Json { get; set; } = new JsonHelpers();<br>}</pre><p>And here’s how we create the IRazorEngineService that utilizes HtmlSupportTemplateBase&lt;T&gt;:</p><pre>var config = new TemplateServiceConfiguration<br>{<br>    BaseTemplateType = typeof(HtmlSupportTemplateBase&lt;&gt;)<br>};<br><br>using (var service = RazorEngineService.Create(config))<br>{<br>    // Call RunCompile here using the template and view model<br>}</pre><p>And that’s pretty much it. Now that we told RazorEngine what <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.htmlhelper.raw?view=aspnet-mvc-5.2">Html.Raw</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.helpers.json.encode?view=aspnet-webpages-3.2">Json.Encode</a> are supposed to do, it’s able to compile the template just fine.</p><p>This goes without saying, but this can be extended to anything else that you have in your template.</p><p>Thank you for reading and I hope this saves you a bit of time if you’ve encoutnered the same problem that I have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=226183543b35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a Serilog enricher that adds HTTP information to your logs]]></title>
            <link>https://medium.com/@kerimemurla/how-to-create-a-serilog-enricher-that-adds-http-information-to-your-logs-1588fc83ccbb?source=rss-b08e1badd92b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1588fc83ccbb</guid>
            <category><![CDATA[serilog]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Kerim Emurla]]></dc:creator>
            <pubDate>Tue, 24 May 2022 07:29:54 GMT</pubDate>
            <atom:updated>2022-05-24T07:29:54.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*dttvPTm-lHW3iWriXklm7A.png" /></figure><h3>What is a Serilog enricher and what is it used for?</h3><p>A Serilog enricher gives us the ability to dynamically add useful, contextual properties to our logs. It is one of those things that makes Serilog more than just a logging API.</p><p>A number of pre-built enrichers can be found on the <a href="https://github.com/serilog/serilog/wiki/Enrichment">Github</a> page of Serilog. However, today, we’re going to write our own. Ours will enrich our logs with properties from the HttpContext.</p><p>After getting familiar with what an enricher is, let’s get into writing one of our own…</p><h3>The setup</h3><p>For the purpose of being IDE-agnostic, we’re going to use the <a href="https://docs.microsoft.com/en-us/dotnet/core/tools/">.NET CLI</a> to create our project and add the necessary NuGet packages. For the purpose of demonstrating how to create the enricher, we are going to create a Web API project using ASP.NET Core 6 and we’ll target C# 10.</p><p>The first command we are going to execute is the one that’ll create our project:</p><pre>dotnet new webapi --name HttpEnricher</pre><p>Having our project created and ready to go, next, we’ll have to install the necessary NuGet packages to make it all work.</p><p>First things first, we’ll need to add the <a href="https://github.com/serilog/serilog">Serilog</a> package itself. We can do that by executing the following command:</p><pre>dotnet add package Serilog</pre><p>After having Serilog installed, we’ll essentially need to log somewhere. In order to not complicate things more than necessary, we’ll log into the console. For the purpose of logging into the console, we’ll use one of the available Serilog <a href="https://github.com/serilog/serilog/wiki/Provided-Sinks">sinks</a>. We can install the <a href="https://www.nuget.org/packages/serilog.sinks.console/">Serilog.Sinks.Console</a> using the following command:</p><pre>dotnet add package Serilog.Sinks.Console</pre><p>That puts us in a good place, where we have the Serilog itself and a place where we can see our logs. In order for everything to come together, we’ll need to install one last package, which will integrate Serilog with ASP.NET Core itself. The package is called <a href="https://www.nuget.org/packages/Serilog.AspNetCore/">Serilog.AspNetCore</a> and we can install it using the following command:</p><pre>dotnet add package Serilog.AspNetCore</pre><p>Now that we have our project created, and all the necessary NuGet packages installed, we can start digging into the code…</p><h3>Creating the enricher</h3><p>A Serilog enricher is a class that implements the ILogEventEnricher. The ILogEventEnricher interface has a single method called Enrich, that we’re going to go ahead and implement. Here’s what the implementation looks like:</p><pre>public class HttpContextEnricher : ILogEventEnricher<br><strong>{<br>    </strong>private readonly IHttpContextAccessor _httpContextAccessor<strong>;<br><br>    </strong>public HttpContextEnricher(IHttpContextAccessor httpContextAccessor)<br>    {<br>        _httpContextAccessor = httpContextAccessor<strong>;<br>    </strong>}<br>    <br>    public void Enrich(LogEvent logEvent<strong>, </strong>ILogEventPropertyFactory propertyFactory)<br>    {<br>        var httpContext = _httpContextAccessor.HttpContext<strong>;<br><br>        </strong>if (httpContext is null)<br>        {<br>            return<strong>;<br>        </strong>}<br><br>        var httpContextModel = new HttpContextModel<br>        {<br>            Method = httpContext.Request.Method<br>        }<strong>;<br><br>        </strong>logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(&quot;HttpContext&quot;<strong>, </strong>httpContextModel<strong>, </strong>true))<strong>;<br>    </strong>}<br><strong>}</strong></pre><pre>public class HttpContextModel<br><strong>{<br>    </strong>public string Method { get<strong>; </strong>init<strong>; </strong>}<br><strong>}</strong></pre><p>The HttpContextModel is a class that contains the properties we’re interested in. For the sake of keeping things simple, we’re going to use only the Method property. You are free to add as many properties as you’d like to that class.</p><p>Having our enricher class implemented, the next is to add it to the DI container alongside the IHttpContextAccessor.</p><h3>Setting up the logger</h3><p>The first thing we’re going to add is the HttpContextAccessor in order for us to be able to inject it into the constructor of our enricher. We can do that with the following line of code:</p><pre>builder.Services.AddHttpContextAccessor()<strong>;</strong></pre><p>Next, we’ll need to register the enricher class itself into the DI container. We can do that with the following line of code:</p><pre>builder.Services.AddSingleton&lt;HttpContextEnricher&gt;()<strong>;</strong></pre><p>Now that we have the necessary dependencies registered, we can go ahead and set up the logger itself.</p><p>Serilog provides a very convenient overload of the <a href="https://github.com/serilog/serilog-extensions-hosting/blob/dev/src/Serilog.Extensions.Hosting/SerilogHostBuilderExtensions.cs#L133">UseSerilog</a> extension method that allows us to use the IServiceProvider. Remember that we’ve registered our enricher class into the DI, so we’re going to need the IServiceProvider to get a hold of an instance of the class itself and tell Serilog to enrich the logs with it. Here’s how we are going to use the <a href="https://github.com/serilog/serilog-extensions-hosting/blob/dev/src/Serilog.Extensions.Hosting/SerilogHostBuilderExtensions.cs#L133">UseSerilog</a> extension method:</p><pre>builder.Host.UseSerilog((_<strong>, </strong>serviceProvider<strong>, </strong>loggerConfiguration) =&gt;<br>{<br>    var enricher = serviceProvider.GetRequiredService&lt;HttpContextEnricher&gt;()<strong>;<br>    <br>    </strong>loggerConfiguration<br>        .Enrich.FromLogContext()<br>        .Enrich.With(enricher)<br>        .WriteTo.Console(outputTemplate: &quot;[{Timestamp:HH:mm:ss} {Level:u3}] {HttpContext} {Message:lj}{NewLine}{Exception}&quot;)<strong>;<br></strong>})<strong>;</strong></pre><p>And with that, we have our logger fully set up. An important thing to notice in the configuration is that we’ve changed the output template. The reason being is that if are to see the HttpContext property our enricher added in our logs, we have to add it to the output template as Serilog doesn’t take care of that for us.</p><p>Let’s go ahead and try logging something…</p><p>We’ll add the following line of code to the Get method of the WeatherForecastController:</p><pre>_logger.LogInformation(&quot;Getting the forecast&quot;)<strong>;</strong></pre><p>After sending a request to the endpoint we see the following log:</p><pre>[08:35:19 INF] HttpContextModel { Method: &quot;GET&quot; } Getting the forecast</pre><p>It looks like we’ve successfully enriched our logs with the HTTP method.</p><h3>Conclusion</h3><p>The technique demonstrated is not specific to the HttpContext. The ability to register the enricher class into the DI means that we’re free to inject anything we’d like into the enricher.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1588fc83ccbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>