ASP.NET Core – Get The Current Version of ASP.NET Core MVC using Reflection

When developing an ASP.NET Core application/library for everyone to use, you can need to get the current version of ASP.NET Core MVC for having special processes corresponding to each version or statistical purposes, etc. In this article will show you how to do this by using the Reflection approach.

Firstly, we need to get the fully qualified name a class, which exists in all versions of the Microsoft.AspNetCore.Mvc assembly. And Microsoft.AspNetCore.Mvc.Controller class is one of them. Here is how to get the fully qualified name of this Controller class.

string fullyQualifiedName = typeof(Microsoft.AspNetCore.Mvc.Controller).AssemblyQualifiedName;

we will get the result like this:

Microsoft.AspNetCore.Mvc.Controller, Microsoft.AspNetCore.Mvc.ViewFeatures, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60

As you see, the above contains the version of ASP.NET Core MVC, you can now extract it from this string, but it is not the way we want to guide you in this article and it also is not a good way to do this we think. Instead, we will use a better way using Reflection.

Let’s implement a helper AspNetCoreMvcVersion method as shown right below:

AspNetCoreHelper.cs
using System;
using System.Reflection;

namespace MyAspNetCoreWebApp.Helpers
{
    public class AspNetCoreHelper
    {
        public static string AspNetCoreMvcVersion
        {
            get
            {
                // unknown mvc core version
                string mvcCoreVersion = "0";

                try
                {
                    string mvcCoreClass = "Microsoft.AspNetCore.Mvc.Controller, Microsoft.AspNetCore.Mvc.ViewFeatures";
                    mvcCoreVersion = Type.GetType(mvcClass).Assembly.GetName().Version.ToString();
                }
                catch (Exception)
                {
                    // the mvc core Controller class does not exist in the app
                }

                return mvcCoreVersion;
            }
        }
    }
}

The above code we just use Microsoft.AspNetCore.Mvc.Controller, Microsoft.AspNetCore.Mvc.ViewFeatures as the argument for Type.GetType method, do not need to use other things in the Controller‘ fully qualified name.

This helper method returns the current version of ASP.NET Core MVC and “0” version in case the Controller class does not exist in the application, it may be due to the Microsoft.AspNetCore.Mvc assembly is not referenced in the application.

OK, we are done, let’s see how it works:

string mvcCoreVersion = AspNetCoreHelper.AspNetCoreMvcVersion;

Here are some results when running on

  • Asp.Net Core v2.2 web application:
2.2.0.0
  • Asp.Net Core v2.1 web application:
2.1.0.0
  • Asp.Net Core v1.0 web application:
1.0.0.0

Leave a Reply

avatar