Authentification with Active Directory (AD) with Asp.Net MVC

With Visual Studio 2013, you cannot simply choose “Intranet WebSite” to create a default website that use Active Directory. Nevertheless, a wizard allow you to create it. First, select create a new project and select a web application.

CreateNewWebApplication1

Second, you need to select MVC and to click change authentication.

CreateNewWebApplication2

This will result to a page where you will be able to select Organisation Authentification. Select On-Promise. This will let you specify the active directory URI.

CreateNewWebApplication3

And that’s it.

You can also do it more manually. It’s good to know because if you have to configure IIS, you will have to do some configuration. First, you need to disable anonymous authentication and allow windows authentication.

The web.config also need to tell that we use windows authentication.

<system.web>
  <authentication mode="Windows" />

  <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
   <providers>
      <clear />
      <add 
          name="AspNetWindowsTokenRoleProvider"
          type="System.Web.Security.WindowsTokenRoleProvider" 
          applicationName="/" />
   </providers>
  </roleManager>
</system.web>

This allow the use of the Authorize attribute over controllers and methods.

[Authorize(Roles = "YOURDOMAIN\\Group1, YOURDOMAIN\\Group2")]
public ActionResult YourMethod()
{
     //...
}

If you want to allow the user to log with the form instead of being automatically logged in, you need to specify a connection string in the web.config.

<connectionStrings>
  <add name="ADConn" connectionString="LDAP://YourConnection" />
</connectionStrings>

Then, you need to setup the membership provider.

<membership defaultProvider="ADMembership">
  <providers>
    <add name="ADMembership"
         type="System.Web.Security.ActiveDirectoryMembershipProvider,
               System.Web,
               Version=2.0.0.0, 
               Culture=neutral,
               PublicToken=b03f5f7f11d50a3a"
         connectionStringName="ADConn"
         connectionUsername="domain/user"
         connectionPassword="pwd" />
  </providers>
</membership>

WCF Inspector for logging

We have already talk about how to log every call of your WCF service with a custom factory for all your WCF service. This is a good way to log or to verify access to all your service methods. The main point was to create a factory which is called every calls it’s done. Once it generated, it creates a new service behavior to which it needs to have a new operation behavior and invoker.

This time, the solution to log every method call it is by using inspector. An inspector is a filter that is executed before and after a request is executed. First of all, this solution works by configuring in the web.config a behavior. An entry to system.serviceModel > extensions > behaviorExtensions needs to be added and will be used to system.serviceModel > endpointBehaviors > behavior.

Here is an example of the web.config:

<system.serviceModel>
     <extensions>
            <behaviorExtensions>
                <add name="myLogBehavior"
                     type="MyServiceA.LogFileBehaviorExtensionElement, MyServiceA" />
            </behaviorExtensions>
        </extensions>
...
 <services>
      <service name="MyServiceA.Service1">
        <endpoint address="" 
                  behaviorConfiguration="behavior1" 
                  binding="wsHttpBinding"
                  bindingConfiguration="" 
                  contract="MyServiceA.IService1" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
          <behavior name="behavior1">
              <myLogBehavior logFileName="c:\log.txt" />
          </behavior>
      </endpointBehaviors>

...

Three parts are important. The first one is the extension that define the behavior extension. This allow us to create configuration outside the code that is defined inside the web.config. A name is specify that is referred later inside the web.config, and the second attribute is the name of the extension inside the code. In the example above, the code display a LogFileBehaviorExtensionElement that is inside the MyServiceA namespace. The second part is the service’s endpoint itself. This is where we specify the contract, the binding and also the behaviorConfiguration. This behavior configuration lead us to the third important part which is the behavior that we have created. The third part is the endpointBehaviors where it specify the behavior. In the example, it’s named “behavior1” which is referenced inside the endpoint. Inside this third part, the myLogBehavior define a parameter where it’s the file log name.

The next step is to create the behavior extension element inside the code.

/// <summary>
/// Allow to join the end point behavior via web.config + parameter for the web.config
/// </summary>
public class LogFileBehaviorExtensionElement : BehaviorExtensionElement
{
    [ConfigurationProperty("logFileName")]
    public string LogFileName
    {
        get
        {
            return (string)base["logFileName"];
        }
        set
        {
            base["logFileName"] = value;
        }
    }

    protected override object CreateBehavior()
    {
        return new LogOutputBehavior(this.LogFileName);
    }

    public override Type BehaviorType
    {
        get
        {
            return typeof(LogOutputBehavior);
        }
    }
}

As you can see, this contain a configuration property which is the attribute of the file name defined in the web.config. It also create the behavior. The next class to create is the endpoint behavior. This is where we add the inspector to the endpoint. This mean that every method of the service will have the inspector hooked to them. If it’s not the desired behavior, it’s also possible to hook an inspector with a custom attribute.

/// <summary>
/// Allow to hook an inspector
/// </summary>
public class LogOutputBehavior : IEndpointBehavior
{
    private string logFileName;
    public LogOutputBehavior(string logFileName)
    {
        this.logFileName = logFileName;
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
            
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        LogOutputMessageInspector inspector = new LogOutputMessageInspector(this.logFileName);
        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

The behavior create the inspector.

/// <summary>
/// The inspector
/// </summary>
public class LogOutputMessageInspector : IDispatchMessageInspector
{
    private string logFileName;
    public LogOutputMessageInspector(string logFileName)
    {
        this.logFileName = logFileName;
    }
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
        request = buffer.CreateMessage();
        File.AppendAllText(this.logFileName, "["+DateTime.Now+"] Request : " + request.ToString());
        return null;
    }
    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
        reply = buffer.CreateMessage();
        File.AppendAllText(this.logFileName, "[" + DateTime.Now + "] Reply : " + reply.ToString());
    }

}

This is the inspector! We have the AfterReceiveRequest, that is called just before the method of the controller in entered and the BeforeSendReply that is called after the method is called. This Allow you to create an entry in the log and to know the starting and ending time of the call. You can also have access to the message sent. This is in soap format. Here is an example:

[2013-11-09 14:21:01] Reply : 
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
  <s:Header>
    <a:Action s:mustUnderstand="1">http://tempuri.org/IService1/GetDataResponse</a:Action>
    <a:RelatesTo>urn:uuid:af68f512-6948-4c2f-b0a8-36cbd9799ebf</a:RelatesTo>
  </s:Header>
  <s:Body>
    <GetDataResponse xmlns="http://tempuri.org/">
      <GetDataResult>You entered: 0</GetDataResult>
    </GetDataResponse>
  </s:Body>
</s:Envelope>

You have all the information you want. In real, you would like to parse this xml to get the method name which is inside the envelope>header>action or by using the Message property Headers and use the Action property to get the method called. It’s also possible to get HttpRequest information is the endpoint is an http one.

MessageWithHttpRequest

This is it for WCF inspector.

Entity Framework SELECT VALUE Q with ESQL, why?

When you are using Entity Framework and want to pass a query string manually, you have to use SELECT VALUE XXX FROM … why? This is a good question and often we see SELECT VALUE Q FROM, why Q? In fact, it can be anything but a single word. ESQL allow to do a select with a row wrapper or without. When using VALUE, it adds a wrapper which create a return of a materialized data record. Entity Framework handle this materialized data record to bind the result into a context object. Without the VALUE, you do not have any wrapper and you get back a set of rows.

Here is an example with SELECT VALUE. We receive a strongly typed set of object.

string queryString = "SELECT VALUE q from table1.attr1 as q";
ObjectQuery<T> query = context.CreateQuery<T>(queryString);

You can also specify which field you return if you do not want every fields.

string queryString = "SELECT VALUE row (q.Field1 as Field1, q.Field2 as Field2) from table1.attr1 as q)";
ObjectQuery<T> query = context.CreateQuery<T>(queryString);

This time, the keyword “row” is required because it’s a reserved keyword by ESQL. ROW constructs an anonymous value.

And an example that return a set of rows. As you can see, we have a DbDataRecord.

string queryString = "SELECT q table1.attr1 as q";
ObjectQuery<DbDataRecord> query = context.CreateQuery<DbDataRecord>(queryString);

Most of the time, you will use the SELECT VALUE q FROM … The use of ESQL must be as low as you can because it opens a door to have SQL Query inside your code, which the ORM is there to abstract. Nevertheless, sometime, for optimization, ESQL is perfect.

Automapper bind automatically property of property by concatenating property name

This title has a lot of properties, I know. Today, I’ll show you with a simple unit test that Automapper bind properties’ property automatically with their name. For example, a class that has a property called User that has by itself a property called FirstName and LastName, will auto-bind to MyMappedClass.UserFirstName and MyMappedClass.UserLastName.

[TestClass]
public class UnitTest1
{
	public class ClassA
	{
		public ClassA()
		{
			this.PropertyA = new ClassAB();
		}

		public ClassAB PropertyA { get; set; }
	}

	public class ClassAB
	{
		public int Id { get; set; }
		public string Suffixe { get; set; }
		public string NotTheSame { get; set; }
	}

	public class ClassB
	{
		public int PropertyAId { get; set; }
		public string PropertyASuffixe { get; set; }
		public string NotReallyTheSame { get; set; }
	}

	[TestMethod]
	public void TestMethod1()
	{
		var c = new ClassA();
		c.PropertyA.Id = 123;
		Mapper.CreateMap<ClassA, ClassB>();
		var mapped = Mapper.Map<ClassA, ClassB>(c);
		Assert.AreEqual(c.PropertyA.Id,mapped.PropertyAId);
		Assert.AreEqual(c.PropertyA.Suffixe,mapped.PropertyASuffixe);
		Assert.IsNull(mapped.NotReallyTheSame);
	}
}

AutoMapperSuccess

The code above show you this reality. The ClassA is mapped to ClassB. Class A doesn’t specify any Automapper configuration, just a single CreateMap without options. Nevertheless, Automapper is bright enough to bind Id and Suffixe from ClassA to ClassB. This is because the name of those properties are present in the mapped ClassB class with the concatenation of the two properties name.

Asp.Net MVC error 404 The request filtering module is configured to deny a request where the query string is too long.

If you create a new MVC projet and hit F5 to start the application. As you may know by now, Visual Studio 2013 doesn’t have Cassini, the internal web server inside Visual Studio. So, IIS Express is quickly automatically configured and the default website start.

RequestQueryStringIsTooLong

Unfortunatly, if I do nothing, I am having a issue with query string being too long. This is because it redirect to the login page which redirect to the login page and so on.

So far, I haven’t found solution, neither StackOverFlow. But, if you are using IIS, everything works. Personally, I am always using IIS, but I am still curious why the IIS express, even with a brand new project doesn’t work.

EDIT

I finally found that in IIS Express configuration file (located inside your document setting), I had windows authentication enabled. You need to remove this and to use anonymous authentication.

Two differents approaches to save data from Javascript to Asp.Net MVC

They are more than two approaches to send data from Javascript with Ajax to Asp.Net MVC. Today, I’ll present you one that use dynamic and one that use DTO (data transfert object). The first approach is faster because it requires less code but is dynamic which open the door to several problems. Before anything, let see the Javascript that will be used by both approaches.

$(document).on("click", "#btnSaveOrder", function () {
    var button = $(this);
    $(button).attr('disabled', 'disabled');
    $('.loadingAnimationfixed').show();
    var listIdOrdered = [];
    $('#sessiongrid tbody tr').each(function () {
        listIdOrdered.push($(this).attr("data-workoutsessionid"));
    });

    var toSave = {
        'OrderedWorkoutSessionList': listIdOrdered
        ,'WorkoutId': $('#Id').val()
    }; 

    $.ajax(
        {
            url: "/WorkoutSession/SaveWorkoutSessionOrder",
            type: "POST",
            data: JSON.stringify(toSave),
            success: function (response, status, xhr) {
                successMessage(response.Status);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errorThrown == "Forbidden") {
                    errorMessage("Forbidden access");
                } else {
                    errorMessage('An error occurred please retry.');
                }
            }
            , complete: function () {
                $(button).removeAttr('disabled');
                $('.loadingAnimationfixed').hide();
            }
        }
    );

    return false; //Prevent button to submit the form
});

The code bind with JQuery a click event to the button with the ID “btnSaveOrder”. We disable the button and display a loading animation division. This is so far good practice. It disallows the user to click twice on the button and it displays to the user what’s going on. Next, we are building from the user interface a list of id. The situation here is that we need to save a list of ID to the database in a specific order. The line that initialize the tosave variable contains a list of all ID which is ordered, then a variable of the current workout. So, we have an object that contain a workout ID with a list of workout session ID that is ordered as FIFO (first in first out) list. This object need to be sent to the server to be saved. This is done by the JQuery Ajax method. First, we specify the URL and the method to contact the server. Second, we specify the object to send and we transform the Json into a string. Finally, we display a success message or an error message. In both case, we enable the button and remove the animation with the complete method. From this code, we know that from the server side we need to have a POST action that is called SaveWorkoutSessionOrder which take a class with 2 properties, one is a list of integer and one is an integer.

The first approach to handle this is to go fast and to not create a class that contain a list of integer and one integer. We can do it by using the dynamic keyword.

[HttpPost]
public JsonResult SaveWorkoutSessionOrder()
{
	dynamic json = JsonConvert.DeserializeObject(Request.Form.Get(0));

	int order = 1;
	var workout = new Workout { Id = json.WorkoutId };
	workout.Sessions = new List<WorkoutSession>();

	foreach (var id in json.OrderedWorkoutSessionList)
	{
		workout.Sessions.Add(new WorkoutSession { Id = id, Order = order++});
	}

	try
	{
		ServiceFactory.Workout.UpdateSessionOrderOnly(workout);
	}
	catch (DataNotFoundException)
	{
		throw new HttpException((int)HttpStatusCode.Forbidden,"Cannot update the session");
	}
	return Json(new { Status="Saved" });
}

The first thing we remark is that the method doesn’t contain any parameter. This is because we won’t allow the model binder to act but deserialize it manually inside the method. This is what the first line of the method is doing with the JsonConvert.DeserializeObject. We need to get the Request object and to get the first element of the form which is the one sent by Javascript with the Ajax calls. The return value of the deserialization go to a dynamic variable. This allow us to skip the creation of a concrete class for the list of integer and integer. Then, we can use the variable but you won’t have any intellisence. You need to be sure to write correctly the property name of this dynamic variable with the same name as the Javascript prototype. If you do, everything will be fine in the execution. Nevertheless, this is not an optimal way to develop a enterprise application because of many problem. Yes, it’s faster, but the cost is heavier in the long term.

As you can see, we do not have a parameter to this controller’s action. Even if it’s not dramatic, it’s harder to unit test because it requires to mock the Request object. The second problem is with the dynamic itself. The use of dynamic weak the entire method. The problem is that error is not detected until execution. If you are unit testing with a full coverage this method, you shouldn’t have a problem. The last problem is that we are deserializing inside the controller’s action instead of delegating the process to the Model Binder. Every mapping between http request and controller’s methods are done by the Model Binder. The cohesion of your controller is compromise and may come a problem later on in the maintenance phase of your system.

To solution is to change the controller to take a parameter that will be deserialized by the Model Binder of Asp.Net MVC and will give us a strongly typed object. This one will be easily testable since we will be able to pass in our tests a parameter.

[HttpPost]
public JsonResult SaveWorkoutSessionOrder(WorkoutSessionOrder workoutSessionOrder)
{
	int order = 1;
	var workout = new Workout { Id = workoutSessionOrder.WorkoutId };
	workout.Sessions = new List<WorkoutSession>();

	foreach (var id in workoutSessionOrder.OrderedWorkoutSessionList)
	{
		workout.Sessions.Add(new WorkoutSession { Id = id, Order = order++});
	}

	try
	{
		ServiceFactory.Workout.UpdateSessionOrderOnly(workout);
	}
	catch (DataNotFoundException)
	{
		throw new HttpException((int)HttpStatusCode.Forbidden,"Cannot update the session");
	}
	return Json(new { Status="Saved" });
}

As you can see, the first signature as changed to have a parameter. That mean that we need to provide this data from the Javascript. In fact, we were sending this object previously but this time we have to specify the data type to indicate to Asp.Net MVC framework what information we are sending to deserialize. To mark the data sent to be JSON format, we need to add this line in the Ajax’s call : contentType: ‘application/json’.

$(document).on("click", "#btnSaveOrder", function () {
    var button = $(this);
    $(button).attr('disabled', 'disabled');
    $('.loadingAnimationfixed').show();
    var listIdOrdered = [];
    $('#sessiongrid tbody tr').each(function () {
        listIdOrdered.push($(this).attr("data-workoutsessionid"));
    });

    var toSave = {
        'OrderedWorkoutSessionList': listIdOrdered
        ,'WorkoutId': $('#Id').val()
    }; 

    $.ajax(
        {
            url: "/WorkoutSession/SaveWorkoutSessionOrder",
            type: "POST",
            data: JSON.stringify(toSave),
            contentType: 'application/json',
            success: function (response, status, xhr) {
                successMessage(response.Status);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errorThrown == "Forbidden") {
                    errorMessage("Forbidden access");
                } else {
                    errorMessage('An error occurred please retry.');
                }
            }
            , complete: function () {
                $(button).removeAttr('disabled');
                $('.loadingAnimationfixed').hide();
            }
        }
    );

That’s it! Now we have seen two different approaches. The last one is the one you should use every time because it’s strongly typed, easier to test and won’t compile with possible error like the one with Dynamic which will crash on execution if a typo is done.

How to migrate from ASP.NET MVC 4 to ASP.NET MVC 5

The new version of MVC is out since few weeks. If you have Microsoft Visual Studio 2013 and create a new web application, you will notice some improvements. First, MVC default version is now version 5 and not version 4. This come with a brand new razor version which is the third. Also, Entity Framework is now at version 6. Before going further, notice that if you are migrating to MVC5 than some older version of other assembly won’t be compatible. For example, razor version 2 won’t work with MVC5.

This is not an easy step to do, migrating, but if you have your MVC4 already up-to-date and have used Nuget for your external libraries, the process won’t be that hard. The first step is to make sure you commit all your code to your repository. Preferably, label it with “Last Version MVC4”. This way, if something is wrong, you will be able to go back and start from scratch.

PackageManagerConsole

The second step is to run Nuget to update every packages. This can be done with a single statement in the Nuget Console.

PM> Update-Package

This may take several minutes if you use a lot of package. This will do about half of the job. You will need to do this for every of your project that use package from Nuget. A good practice is to have always referenced your external library with Nuget. Even if you are using the same package from some of your projects, this won’t duplicate them in your solution/packages.

The third step is to be done in every of your project. I suggest you start from your web site project since it’s the one that will have the most job to do. Open the web.config of the web project. Verify that you have Entity Framework set to version 6. The information is set inside configuration>configSections inside a section named “EntityFramework”.

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
...................

As you can see, the version MUST be set to 6.0.0.0 and in fact it should have been modified by the Nuget update that we have done earlier. If it’s not, go in your project reference and be sure that you have a reference to EntityFramework.dll.

EntityFrameworkVersion6

The screenshot show you that not only the version is set to version 6.0.0.0 but that the version 6 of Entity Framework has a new dll called “EntityFramework.SqlServer”. This is now required.

The next step is to go lower in your web.config to the appSetting section. You need to update the version of webpages from 2.0.0.0 to 3.0.0.0


Then, you need to set the framework to 4.5.1 (if you want to be all up to date). This can be done in the web.config also inside the configuration tag, under system.web:


  <system.web>
    <compilation debug="true" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.1"/>

Before going any further in the web.config. Do not forget to open ALL your project to go in the properties of the project and to select the Target Framework to 4.5.1.
ApplicationPropertiesTargetFramework

Back to the web.config, we have the runtime tag to update. Here is my runtime information, yours should be almost the same.

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
	<dependentAssembly>
		<assemblyIdentity name="WebMatrix.WebData" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="WebMatrix.Data" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.Razor" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
		<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
		<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
		<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="AutoMapper" publicKeyToken="be96cd2c38ef1005" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="Microsoft.Practices.Unity" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2"/>
	</dependentAssembly>
</assemblyBinding>

This tell the .Net compiler to use the new version if a reference is made to an older version. You can find information through MSDN concerning Assembly Unification.

Now, do that in all your web.config that contain similar XML elements. Once it’s done, go into the view folder. This one also should contain a web.config. You need to change some version number here too. Here is one of my view folder (you can have few because of area).

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5Install-Package -Id  Microsoft.AspNet.WebHelpers.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

You have 3 entries to change for razor. You need to change version 2.0.0.0 to version 3.0.0.0. Also, System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc need to be to 5.0.0.0. Then, under pages you have 3 others change concerning MVC that need to be to version 5.

The last modification that is require to use MVC5 is to open with note pad the project file of the web. Search for ProjectTypeGuids and remove the GUID for MVC4 : {E3E379DF-F4C6-4180-9B81-6769533ABE47}.

You won’t have the stuff that a brand new MV5 project has like BootStrap but this can be added later on. What you have is a project up-to-date with Microsoft MVC framework 5, Entity Framework 6 and using the .Net Framework 4.5.1