How to register Model Builder without having to manually add them one by one

When you are using Entity Framework, you must have a class that inherit DbContext class at some point. Multiple options is offer to you to register to Entity Framework (EF) definition of your entities.

The one we see in tutorial is based on the overridden method OnModelCreation that has a single parameter of type DbModelBuilder. This is the entry point for all way to proceed with registration. Nevertheless, in tutorial the configuration is done directly in the method. The following code shows how it is usually done. For the purpose of being short, only a single primary key is defined for a single entity. The fact is that method can become very big.

public class MyDbContext : DbContext
{
	protected override void OnModelCreating(DbModelBuilder modelBuilder)
	{
		modelBuilder.Entity<YourEntity>().HasKey(d => d.Id);
		base.OnModelCreating(modelBuilder);
	}
}

This is why, the best practice is to have a single class for every entity configuration. This is done by inheriting every classes by EntityTypeConfiguration.

public class YourEntityConfiguration : EntityTypeConfiguration<YourEntity>
{
	public YourEntityConfiguration()
	{
		this.HasKey(d => d.Id);
	}
}

Once you have your classes defined, the OnModelCreating can register them.

public class MyDbContext : DbContext
{
	protected override void OnModelCreating(DbModelBuilder modelBuilder)
	{
		modelBuilder.Configurations.Add(new YourEntityConfiguration());
		base.OnModelCreating(modelBuilder);
	}
}

The problem is that you have to remember to register the entity and also that this method can become very huge on big project. Concerning the possibility to forget to register, Entity Framework (EF) will raise an exception saying that it does not know the entity type. It is not a big deal and the message is quite easy to understand. However, having to add this line of code become something to do in a big list of things to do. To keep it simpler, Entity Framework team thought that we could simply specify which assembly every configuration are and to look up for every classes that inherit the EntityTypeConfiguration.

public class MyDbContext : DbContext
{
	protected override void OnModelCreating(DbModelBuilder modelBuilder)
	{
		modelBuilder.Configurations.AddFromAssembly(Assembly.GetAssembly(GetType())); //Current Assembly
		base.OnModelCreating(modelBuilder);
	}
}

The above example shows that configurations are added from an assembly. It takes a single parameter that is the assembly to look up. If you want the current assembly, use Assembly.GetAssembly(GetType()).

Migrating Asp.Net MemberShip to Asp.Net MVC Identity for authentification

I was using WebMatrix with the Gym Workout project. But, it wasn’t a clean way to handle authentification. It was in the middle of the old membership with a new flavor. However, since Microsoft is going with the new One Asp.Net Owin Identity framework which allow to use claims but also to be dissociate from Microsoft Sql Server make it more appealing. It’s also on the frame of OWIN, so we have almost all positive features without the negative parts. Finally, Identity does have the clean way to have custom field to extend default username/password attribute. It’s clean because it creates specific columns for each field. So, if you have an existing Asp.Net MVC, how do you upgrade to the Identity framework for authentification? This is what I will explain in this Identity tutorial.

First, some libraries are required.

  • Microsoft.AspNet.Identity.EntityFramework
  • Microsoft.AspNet.Identity.Core
  • Microsoft.AspNet.Identity.OWIN

This can be found by using Nuget with the following command:

PM> Install-Package Microsoft.AspNet.Identity.Core
PM> Install-Package Microsoft.AspNet.Identity.Owin
PM> Install-Package Microsoft.AspNet.Identity.EntityFramework
PM> Install-Package Microsoft.Owin.Host.SystemWeb

The next step was to get rid of everything concerning the user which was in its own class called for the project “UserProfile”. Instead, I created a new class called “ApplicationUser” which inherit from the default one of Identity framework. I removed the WebUserProvider because now, it will use Entity Framework to get user information. Providers are not required and everything will go with the service layer, to the data access layer to the database with Entity Framework (EF). The AccountModel (is in fact the view model) still exist which allow to have our custom fields like the Role, Language and Email in the view. Everything is bound to the model class ApplicationUser.

public class ApplicationUser : IdentityUser, ICurrentUser
{
    public ApplicationUser()
    {
        Email = "";
        Language = "";
    }
    public string UserId {
        get { return base.Id; }
        set{} 
    }
    public string Email { get; set; } 
    public string Language { get; set; } 
        
}

Even if the ApplicationUser inherit from IdentityUser which as a Id property, the ICurrentUser that we had previously use the UserId property. This is why this one is defined in ApplicationUser and link to the IdentityUser one. The only thing that we will do later is to ignore this property to not have the data inside the database. We also need to create a ApplicationUserService that contact the Data Access Layer.

A major change concerns the ServiceFactory class which has every entities service classes. Since the Account come from the database and that we do not want to go to the database every time one of the entity require to have something related to the user logged, they need to share the same account. This require a change in the constructor that is going to take in its constructor the IUserProvider which has a property Account. This one is passed to every service constructor.

public class ServiceFactory : IServiceFactory
{
    private IUserProvider _userProvider;
    #region Implementation of IServiceFactory

    public IAccountService Account { get; private set; }
    public IMuscleService Muscle { get; private set; }
    public IWorkoutService Workout { get; private set; }
    public IWorkoutSessionService WorkoutSession { get; private set; }
    public IWorkoutSessionExerciseService WorkoutSessionExercise { get; private set; }

    public IExerciseService Exercise { get; private set; }

    #endregion

    public ServiceFactory(IRepositoryFactory repositoryFactory, IMapperFactory mapperFactory, IUserProvider userProvider)
    {
        _userProvider = userProvider;
        var account = _userProvider.Account;
        Account = new ApplicationUserService(repositoryFactory, mapperFactory);
        Muscle = new MuscleService(repositoryFactory, mapperFactory, account);
        Workout = new WorkoutService(repositoryFactory, mapperFactory, account);
        WorkoutSession = new WorkoutSessionService(repositoryFactory, mapperFactory, account);
        WorkoutSessionExercise = new WorkoutSessionExerciseService(repositoryFactory, mapperFactory, account);
        Exercise = new ExerciseService(repositoryFactory, mapperFactory, Muscle, account);
    }
}

Entities inherit of BaseService.

public abstract class BaseService
{
        public BaseService(IRepositoryFactory repositoryFactory, IMapperFactory mapperFactory, ICurrentUser user)
        {
            Repository = repositoryFactory;
            Mapper = mapperFactory;
            Repository.SetUser(user);
        }

        protected IRepositoryFactory Repository { get; private set; }
        protected IMapperFactory Mapper { get; private set; }
}

When the service is initialized, it uses the injected Repository to set the user that is also injected. Since the ServiceFactory calls the Account once, one call is done to the database. After, it only set the object to the repository which could be used later.

The concept of IUserProvider remains. This is because we will use a WebUserProvider for the Asp.Net MVC and a WebServiceUserProvider.

The Global.asax.cs file changes because it does not use anymore the AuthConfig.RegisterAuth() because the Identity with OWIN does have a Startup page in the App folder.

public partial class Startup
{

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login")
        });
        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    }

     
}

This also require to register the Startup class with another Startup class that is used as a bootstrapper for the OWIN container.

using Owin;

[assembly: OwinStartup(typeof(WorkoutPlanner.Startup))]
namespace WorkoutPlanner
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Notice the assembly instruction that tell which class is used for OwinStartup. It uses two classes but could use one. the only benefit of splitting the class in two is to have one statup entry and the code to configure somewhere else. This could later uncluttered the booting class.

The migration changes also. The Seed method does not use the WebSecurity to initialize default user. It uses the ApplicationUser class with the UserStore and UserManager class that use Entity Framework to work with the database.

To create the database with all Identity classes and all the business classes, the migration command in the package console is required. The

update-database -ConfigurationTypeName "Configuration"

This works because the Configuration class inherit of DbMigrationsConfigurations which allow the migration tool to be executed. It takes the database context to be used. In our case, it’s the one that contains every entities of the application.

public class Configuration : DbMigrationsConfiguration<DatabaseContext>//<DatabaseContext>
{
	public Configuration()
	{
              base.AutomaticMigrationsEnabled = true;
	}

	protected override void Seed(DatabaseContext context)
	{
		var userStore = new UserStore<ApplicationUser>(context);
		var manager = new UserManager<ApplicationUser>(userStore);

		var role = new IdentityUserRole { Role = new IdentityRole(Model.Roles.ADMINISTRATOR) };
		var user = new ApplicationUser() { UserName = "123123", Email = "123123@123.com", Language = "en-US" };
		user.Roles.Add(role);
		IdentityResult result = manager.Create(user, "123123");

		var role2 = new IdentityUserRole { Role = new IdentityRole(Model.Roles.NORMAL) };
		var user2 = new ApplicationUser() { UserName = "qweqwe", Email = "qweqwe@qweqwe.com", Language = "fr-CA" };
		user.Roles.Add(role2);
		IdentityResult result2 = manager.Create(user2, "qweqwe");

		var muscles = new[]{new Muscle { Id = 1, Name = new LocalizedString { French = "Cou", English = "Neck" } },
							new Muscle { Id = 2, Name = new LocalizedString { French = "Épaule", English = "Shoulder" } }
							};


		context.Set<Muscle>().AddOrUpdateRange(muscles);
		//... and so on...
		base.Seed(context);
	}
}

When working with Asp.Net Identity one key is to have your database context class inherit from IdentityDbContext and not directly from DbContext. Otherwise, you will get that keys are not defined for IdentityUserLogin, IdentityUserRole, IdentityUserLogins and IdentityUserRoles.

DataAccessLayer.Database.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
DataAccessLayer.Database.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
public class DatabaseContext :IdentityDbContext<ApplicationUser>, IDatabaseContext

Migrating from Asp.Net Membership to Identity is not something that can be done for the first time under few hours. In fact, it took me around 12 hours to figure out that I had to inherit from IdentityDbContext and to solve several seeding problem. Also, having to use Entity Framework changed a little but how to use the user information. Nevertheless, the time is not exponential since it concerns only users and roles entities. I believe that it should take less than a day for someone who have all the information.

The entity type ApplicationUser is not part of the model for the current context.

If you are using Asp.net Identity (OWIN authentification framework) with a custom user schema you may stumble into an error that you model is not part of the context.

The entity type ApplicationUser is not part of the model for the current context.

NotPartOfTheModelOfTheCurrentContext

This exception is raised if you go to the login screen and try to log in. It occurs if you have a DbContext class that inherit directly to DbContext and not of IdentityDbContext.

Your database context must be aware of Identity tables.

public class DatabaseContext :IdentityDbContext<ApplicationUser>

Having this inheritance solve the problem.

Asp.Net Identity error while seeding with custom field

If you are using the new Asp.Net Identity framework which is working with OWIN, you may fall with a SQL exception. This exception look like this :

System.Data.SqlClient.SqlException: Invalid column name ‘UserId’

SeedingError

The UserId is a column that is ignored in the configuration of the entity. Why does it try to read from it?

Here is how the DbContext looks like:

public class Configuration : DbMigrationsConfiguration<DatabaseContext>
{
	public Configuration()
	{
	}

	protected override void Seed(DatabaseContext context)
	{
		var userStore = new UserStore<ApplicationUser>();
		var manager = new UserManager<ApplicationUser>(userStore);

		var role = new IdentityUserRole { Role = new IdentityRole(Model.Roles.ADMINISTRATOR) };
		var user = new ApplicationUser() { UserName = "123123", Email = "123123@123.com", Language = "en-US" };
		user.Roles.Add(role);
		IdentityResult result = manager.Create(user, "123123");

		var role2 = new IdentityUserRole { Role = new IdentityRole(Model.Roles.NORMAL) };
		var user2 = new ApplicationUser() { UserName = "qweqwe", Email = "qweqwe@qweqwe.com", Language = "fr-CA" };
		user.Roles.Add(role2);
		IdentityResult result2 = manager.Create(user2, "qweqwe");
		
		//...
	}
}

The problem reside on the first line of the seeding method. The UserStore takes in its first parameter the database context. Since I am not explicitly telling the UserStore to take the one passed by parameter, it does not know about the configuration defined in the DatabaseContext.

To solve the problem just change the first line with this line:

	var userStore = new UserStore<ApplicationUser>(context);

Code coverage with Visual Studio 2013

Microsoft Visual Studio has the ability to tell you what is covered by your unit test. Not all edition has this feature, but Premium and Ultimate do.

First of all, where is the code coverage tool in Visual Studio? It’s in the Test menu under Analyze Code Coverage.

TestCoverageMenu

Once done, the Code Coverage Result panel open. You can open this panel by going to Test>Windows>Code Coverage Result if you want to open it later.

This panel indicates the number of code block and the percentage covered by all code. As you can see, event the unit test project is in the statistic (red arrow). What is important is the blue arrow, the project tested. As you can see in the image below, every thing is unit tested (100%).
CodeCoverageResult

Another feature is to display directly into the code which line has been hit and which one has not been hit. Visual Studio and code coverage tool can highlight in green all code that has been reach by unit tests and in red if no test has executed the line. To enable this feature, click on the Code Coverage Result the icon with multiple block.
CodeCoverageButtonForHighlight

Once clicked, you will see the code changing.

CodeCoverageHighlight

I have entitled this post with Visual Studio 2013 but in fact, this is available since 2008 without much change. It’s not well known but very interesting if you are using unit testing.

Using Intellitrace to help debugging your .Net

IntelliTrace is available since Visual Studio 2010 and it’s available on the Ultimate. This may be the reason why it’s not very popular since a lot of developer doesn’t have the ultimate version. Nevertheless, it’s a powerful debugging tool and it has been improved slightly with the 2012 and 2013 version of Visual Studio. In short, IntelliTrace is an enhancement of the traditional breakpoint debugging but not a replacement.

IntelliTrace allows you to have snapshot of step in the time. This mean that if you hit a break point or you have an exception that break the code, IntelliTrace can show you the stack with different value that has been set. The traditional debugging allows you to modify values of variable, IntelliTrace does not. They have both different goal.

intellitrace

The screenshot above shows some information you can get with a simple call to a controller. As you can see, we have information about the MVC routing and also about what SQL Query has been sent to the database. This allow you to not have to use a SQL profiler to know what is sent to the database.

intellitraceSQL

If you double click the line an entry in the Intellitrace, you see the whole detail but also the code window is going to the line where the data has been gathered. In the example above, the code selected is the line that call the repository:

public IEnumerable<Workout> GetAll()
{
     var listModel = Repository.Workout.GetAll().ToList();
     return listModel;
}

To enable the IntelliTrace or to change some option, go in the Tools>Options>Intellitrace.

IntellitraceOption

The default allows IntelliTrace to work with event. This mean that IntelliTrace has been injected in the code and records event like SQL query, http errors, exceptions, etc. It’s possible to collect more information. To enable additional collect of information, in the option select events and call. This will slow down your debugging sessions because it injects additional code inside your code to collect information. However, richer information is recorded.

  • Function name
  • Values of primitive data types passed as parameters and returned value for every methods
  • Values of properties when they are read or changed

Call is reachable by filtering at the top of the IntelliTrace window and also from event. At the button of the event, a link “Calls” is available. If you click on it, the list of calls will be displayed. It looks a lot like the normal debugging .

When to use IsCustomErrorEnabled with Asp.Net MVC

If you are using Asp.Net MVC, your should have a BaseController that every controllers of your project inherit. In this base controller, your should have override the method OnException.

protected override void OnException(ExceptionContext filterContext)
{
    //1) Write log here
    //2) Redirect from the yellow screen of death to a custom nice error page
}

At least, this is what it should have. The step one as nothing to do with the ExceptionContext.HttpContext.IsCustomErrorEnabled. The second step, yes. In fact, when you are developing the yellow screen is very informative.
yellowscreenofdeath

This is why it can be interested to not

protected override void OnException(ExceptionContext filterContext)
{
  if (filterContext.HttpContext.IsCustomErrorEnabled)
  {
     filterContext.ExceptionHandled = true;
     this.View("YourErrorPage").ExecuteResult(this.ControllerContext);
  }
}

IsCustomErrorEnabled is true when in the web.config the customerror is set to true. It’s false when it’s set to false. When the value is set to remoteonly, it’s true when executing on localhost (127.0.0.1) and false when not. It’s possible to use this variable with the IsCustomErrorEnabled and to leverage of it inside your base controller.

To answer the question, when to use IsCustomErrorEnabled with Asp.Net MVC

Tutorial about how to create your first Nuget package

This is a tutorial about how to create your first Nuget package.
NugetLogo

Part 1 : Setupping basic information of Nuget

The first step is to get Nuget.exe. This is required to create the Nuget package but also to create the first draft of the meta data of the package. It’s open source and can be found at CodePlex.

The second step is to create the meta data package. This is where you specify the name of the application, the version of the Nuget and others information. Another very important section of the meta data is the dependencies list. It allows you the specify other package name and version that needs to be installed before installing your package. To get a brand new meta data file, open a Windows console and type .

nuget spec

This will create a new file like the following one.

<?xml version="1.0"?>
<package >
  <metadata>
    <id>Package</id>
    <version>1.0.0</version>
    <authors>Patrick</authors>
    <owners>Patrick</owners>
    <licenseUrl>http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE</licenseUrl>
    <projectUrl>http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE</projectUrl>
    <iconUrl>http://ICON_URL_HERE_OR_DELETE_THIS_LINE</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Package description</description>
    <releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
    <copyright>Copyright 2013</copyright>
    <tags>Tag1 Tag2</tags>
    <dependencies>
      <dependency id="SampleDependency" version="1.0" />
    </dependencies>
  </metadata>
</package>

For my example, it was to transform the open source project that I have published few weeks ago. What I want to transform is the part that is a MVC template. Here is my transformed file.

<?xml version="1.0"?>
<package >
  <metadata>
    <id>DragAndDropMultiSelectorList</id>
    <version>1.0.0</version>
    <authors>Patrick</authors>
    <owners>Patrick</owners>
    <projectUrl>https://github.com/MrDesjardins/DragAndDropMultiSelectorList</projectUrl>
    <iconUrl>https://raw.github.com/MrDesjardins/DragAndDropMultiSelectorList/master/iconNuget.png</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>This nuget package installs the Javascript, the CSS and the Templates to allow to have UIHint to have special control to drag and drop items from an available list of item to a selected list.</description>
    <releaseNotes>First version</releaseNotes>
    <copyright>Copyright 2013</copyright>
    <tags>drag-and-drop </tags>
    <dependencies>
      <dependency id="jQuery" version="2.0.3" />
      <dependency id="jQuery.UI.Combined" version="1.10.3" />
    </dependencies>
  </metadata>
</package>

You can also use this open source project, the Nuget Explorer, that allow you to edit every meta data properties. It also allow you to publish directly to Nuget once you have an account and a API key.

Part 2 : The content of the Nuget package

The next part is the content of the Nuget package. Create a folder with the name “content”. Everything in this folder will be moved to the solution. This mean if you have inside the folder “content” a folder “Content” and inside this one you have “Images” and you set a file “forward.png” that when the Nuget package is installer, the image will be set at this position. For my example, here is the file structure.

treeNugetPackage

The second step of this part is to have some pre-processing. Nuget allows to change part of every file dynamically. This can be done if you rename your file by adding .pp at the end. For example, I want to use the user namespace for 3 files. I change these three files extension and open them to add the namespace tag.

ppFile

namespace $rootnamespace$.ViewModel.Templates.DragAndDropMultiSelector
{
    public interface ISelectorAvailableItemViewModel<TUniqueIdentifierType, TExtendedValueType>
    {
      TUniqueIdentifierType ID { get; set; }
      string Description { get; set; }
      TExtendedValueType ExtendedProperty { get; set; }
    }
}

As you can see the first line contain $rootnamespace$ which will dynamically change the namespace to the user namespace.

The last step of this part is to add a web.config.transform file to add configuration in the web.config if required. In my scenario, nothing was required so I haven’t added it.

Part 3 : Publish the Nuget package

When everything is setup, it’s time to create the Nuget package. This can be done by using the nuget.exe previously downloaded. You need to execute the .nuspec created by the first step.

nuget pack C:\Users\Patrick\Documents\GitHub\DragAndDropMutltiSelectorList\DragAndDropMutltiSelectorList.nuspec

This will create a file called DragAndDropMutltiSelectorList.1.0.0.nupkg (of course it will be your Nuget name and version).
This can be published to Nuget’s website or your own Nuget repository. To do a fast test, open Visual Studio and add a local folder that has your new Nuget package. This way, you will be able to install any local Nuget package inside this folder. To do, go to Manage Nuget Packages For Solution that is located under Tools>Library Package Manager. Then, click Setting at the bottom of the screen. This will popup the option window for Nuget. Here, you can add your folder.

NugetRepositoryLocal

If you double click your package, it will be installed. This allow you to test your package before publishing it on the web. But, once it’s tested, you can publish it on Nuget.org. This step is very fast. You need to create an account, then you upload the .nukg and that’s it. You can find the package that I just created at this url now : https://www.nuget.org/packages/DragAndDropMultiSelectorList/

Asp.Net MVC With the ValidateAntiForgeryToken For Cross Site Request Forgeries

Cross Site Request Forgeries is also know as CSRF. It is a type of malicious exploit that send commands from a user without his consent to another website. CSRF exploits the trust that a site has in a user’s browser. For example, a website could try to execute a form to add something in your Amazon basket! This can be limited by adding an hidden field to a form and a cookie. Both will contain the same value and when the form is submitted the hidden field is compared to the cookie value. If it’s the same value, we know that the user has sent the form. If it’s not, we know it’s a malicious attack.

In Asp.Net MVC, ValidateAntiForgeryToken is a combination of an html helper (hidden field) and attribute(cookie) that allows to verify if the form as been created and sent by the same user.

The first step is to add the HtmlHelper method @Html.AntiForgeryToken() inside the form in your view.

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    //...

This generate an hidden field with the name “__RequestVerificationToken” and an unique value. This is an example of the output generated:

<form action="/House/Create" method="post" novalidate="novalidate">
    <input name="__RequestVerificationToken" type="hidden" value="KPyzBk0KGpjStJR96AVI38AbBujBInJNB-1XH-RwsbuifwgmxnGiF-0R2cMHjcYBiz7yOBUnv0fZwoE2oBwiuKXalBDvsRr2RRG7nmkOsq41">
//...

The code behind the html helper is simple. It creates a MvcHtmlString from the AntiForgery class.

public MvcHtmlString AntiForgeryToken()
{
   return new MvcHtmlString(AntiForgery.GetHtml().ToString());
}

The AntiForgery class contains the GetHtml() used in the html helper but also some validation of the forgery. Both use the class AntiForgeryWorker.

public static HtmlString GetHtml()
{
  if (HttpContext.Current == null)
     throw new ArgumentException(WebPageResources.HttpContextUnavailable);
  else
     return AntiForgery._worker.GetFormInputElement((HttpContextBase) new HttpContextWrapper(HttpContext.Current)).ToHtmlString(TagRenderMode.SelfClosing);
}

The _worker that we see in the code above is of type AntiForgeryWorker. This class is about 139 lines and the core of it is the GetFormInputElement used by the GetHtml.

public TagBuilder GetFormInputElement(HttpContextBase httpContext)
{
    this.CheckSSLConfig(httpContext);
    AntiForgeryToken cookieTokenNoThrow = this.GetCookieTokenNoThrow(httpContext);
    AntiForgeryToken newCookieToken;
    AntiForgeryToken formToken;
    this.GetTokens(httpContext, cookieTokenNoThrow, out newCookieToken, out formToken);
    if (newCookieToken != null)
    this._tokenStore.SaveCookieToken(httpContext, newCookieToken);
    if (!this._config.SuppressXFrameOptionsHeader)
    httpContext.Response.AddHeader("X-Frame-Options", "SAMEORIGIN");
    TagBuilder tagBuilder = new TagBuilder("input");
    tagBuilder.Attributes["type"] = "hidden";
    tagBuilder.Attributes["name"] = this._config.FormFieldName;
    tagBuilder.Attributes["value"] = this._serializer.Serialize(formToken);
    return tagBuilder;
}

This is interesting to see how the value is generated. As we can see, it’s using the serializer to serialize the form token. The form token is build inside the class TokenValidator that take some property of the Identity. I won’t go deeper because it goes a little beyond the scope of the article. Just remember that the token is unique for the user. However, the GetFormInputElement code above is also important for something else. The token store role is to create the cookie which set also the token.

 public void SaveCookieToken(HttpContextBase httpContext, AntiForgeryToken token)
    {
      HttpCookie cookie = new HttpCookie(this._config.CookieName, this._serializer.Serialize(token))
      {
        HttpOnly = true
      };
      if (this._config.RequireSSL)
        cookie.Secure = true;
      httpContext.Response.Cookies.Set(cookie);
    }

The way the ValidateAntiForgeryToken attribute works is by checking to see that the cookie and hidden form field left by the Html.AntiForgeryToken() Html Helper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException.

ValidateAntiforgerytoken

The attribute does have a ValidateAntiForgeryTokenAttribute method that call the AntiForgery class. I have previously mentioned that it has not only the method to get the input but also for validation. Here is where it’s used.

public ValidateAntiForgeryTokenAttribute()
      : this(new Action(AntiForgery.Validate))
{
}

This method go through several method of the framework to end to the ValidateTokens(…) methods that look like the code below.

public void ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken)
{
    if (sessionToken == null)
       throw HttpAntiForgeryException.CreateCookieMissingException(this._config.CookieName);
    if (fieldToken == null)
       throw HttpAntiForgeryException.CreateFormFieldMissingException(this._config.FormFieldName);
    if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken)
       throw HttpAntiForgeryException.CreateTokensSwappedException(this._config.CookieName, this._config.FormFieldName);
    if (!object.Equals((object) sessionToken.SecurityToken, (object) fieldToken.SecurityToken))
       throw HttpAntiForgeryException.CreateSecurityTokenMismatchException();
    string str = string.Empty;
    BinaryBlob binaryBlob = (BinaryBlob) null;
    if (identity != null && identity.IsAuthenticated)
    {
    binaryBlob = this._claimUidExtractor.ExtractClaimUid(identity);
    if (binaryBlob == null)
        str = identity.Name ?? string.Empty;
    }
    bool flag = str.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || str.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
    if (!string.Equals(fieldToken.Username, str, flag ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
        throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, str);
    if (!object.Equals((object) fieldToken.ClaimUid, (object) binaryBlob))
        throw HttpAntiForgeryException.CreateClaimUidMismatchException();
    if (this._config.AdditionalDataProvider != null && !this._config.AdditionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData))
        throw HttpAntiForgeryException.CreateAdditionalDataCheckFailedException();
}

What interest us is all possible exception that are throws. You can see that is can raise HttpAntiForgeryException for several case like if the cookie is missing, which is the case for Cross Site Request Forgeries or if the form doesn’t have the hidden field, or if the token mismatch between the cookie and the form.

All the complexity of the mechanism is hidden by the Asp.Net MVC framework. At the end, you only need to remember to add the html helper to your form and to add the attribute to the action of your controller that receive the form inputs.