Kicking System.Web out of your code – part 1: ASPNET MVC

Being doing some .NET code for a while now, you sure saw how much dependencies your code has on it.

With .NET core coming in sight, but also for optimizing you existing ASP.NET code base, you probably would want to start lowering your dependencies on it…

The first step (but not the smallest) for me is to kick out ASP.NET MVC.

DISCLAIMER: don’t get me wrong, ASP.NET MVC is a great framework for some use cases, but in my search for boot time optimization and lower memory footprint, this is not exactly what I need.

  1. Replacing ASPNET.MVC by RazorEngine

Not having much linked to it anyway, I replaced it with Razor Engine, a decoupled open source version for the MVC Razor engine (that you can also use to render other things than pages: emails, documents…)

Here is a piece of code to end up using the Razor Engine to render html views and use it the way you alwazs used ASP.NET MVC:

HttpRequestMessage extensions first:

public static class HttpRequestMessageExtensions
{
    public static TemplateServiceConfiguration TemplateConfig = new TemplateServiceConfiguration
    {
        TemplateManager = new EmbeddedResourceTemplateManager(typeof(Startup))
    };

    public static IHttpActionResult View<T>(this ApiController controller, string viewName, T model)
    {
        return GetResponseView(controller.Request, viewName, model);
    }

    public static IHttpActionResult GetResponseView<T>(this HttpRequestMessage request, string viewName, T model)
    {
        var service = RazorEngineService.Create(TemplateConfig);

        var result = service.RunCompile($"Views.{viewName}", typeof(T), model);

        return new HtmlActionResult(request, result);
    }
}

Using the extension in a controller:

public IHttpActionResult Index()
{
    var model = new AppModel();
    // filling the model accordingly.
    return this.View("Index", model);
}

Warning: this does not handle partial views, so this has to be managed additionally.

  1. Replace ASPNET.MVC with SPAs

The ultimate goal is to only have service-side code running as services (leveraging ASP.NET Web API), then to build your UI using a front-end stack for that (Angular. React, whichever suits you).

Next step, will be removing Browser HttpBrowserCapabilities dependencies.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *