How to use Angular 2 with ASP.NET 4.5+ / ASP.NET MVC 5

I got the following question in my ng-sydney AngularJS usergroup:

How to setup ng2 with Vs2015 for like mvc/web API?

While many blog posts answer the question for ASP .NET Core, very few answered it for ASP.NET 4.5 / ASP.NET MVC 5. So, here’s what I tried, and seemed to work.

Create a new project in Visual Studio

I found this online project template template Angular2 Mvc5 sample application, and it worked pretty well.

File -- New Project

Run the sample you get to see the output working.

Also, read the template page for workaround to potential issues with Node.

Upgrade the outcome

Unfortunately, the template only gives you Angular 2 RC1 work, with the deprecated router.

Luckily, it’s not too hard to upgrade it!


If you go to the official Angular quickstart, which you can reach by going to, and clicking “Get started”), you can find the package versions you need in 2 ways:

  1. Clicking “live example”, which takes you to the Plunker example page, you can get the latest versions of Angular 2 packages in the system.config.js file.
  2. Scrolling to Step 1 – b, which shows a package.json file you can just copy the dependencies section from.

Once you figure out the version numbers, you need to apply these to the package.json file in the root of the web project, here’s what the dependencies piece looks like for me, for Angular 2 RC 4:

Try running NPM from a command prompt, or go to Visual Studio output window and change “Show output from” to “bower/npm”. If you see errores complaining about a version not existing of some package, the message will tell you what versions are available, and then you can just pick the highest.

For example, I’m excluding replacing the deprecated router from this exercise. So I kept it, and it didn’t have a package for rc4. The error message about that told me that the max version available is rc2, and that seemed to work fine.

The new router also has its own version. You should be able to see that version in the config file like the other Angular files though.

Angular Forms

After that, since Angular forms became a separate module in RC3, this module was not included.

So, first you need to add it, it has a separate version as well. The plunker systemJS file will tell you what. And it’s shown in the above sample.

Then, you also need to add it into your own systemJS config file systemjs.config.js. Just add it to the packageNames definition. It should then look like:

And that’s it. Run the application again. You should still see the demo Todo-list with routing working.

Look at the browser devtools console. You should see a warning that you are using the deprecated forms module (what is available by default), and shows you a link of how to override it.

This means the project is working well with Angular 2 RC4, and the deprecated forms and router.


Next, you should be able to start deleting the sample components to leave for your own application components.

Before you do that, you might want to see how the project template works, including the serverside ASP.NET MVC bits. This will give you some guidance on how to structure your own.

Once you are done, you can remove the deprecated router from application bootstrapping file and from NPM dependencies. Then start using the new router, which we already included in the previous steps.

You should also be good to disable the deprecated forms (those are not a separate NPM module, so that stays the same), by modifying the application bootstrapping code as the link in the browser console tells you.

Good luck :)

How To Include AbcPDF XULRunner Folder As Linked Item In Visual Studio?

I was working on some PDF generation for a customer that used AbcPDF in their ASP.NET MVC website.

The work was to move from basic MVC views written especially for PDF rendering, to reusing the same MVC views we send to the HTML browsers.

With more sophisticated markup, came more CSS styling. The default IE engine seemed to lack a few CSS features we used a lot (example, the :not() CSS selector). So, we decided to use the Gecko engine.

The rendering was much better, with a single exception, that the option to choose media type (screen, print) could not be switched. It had to always be print. I guess a few other browser settings were not applicable as well.


All I needed to do, to add Gecko, was to install the ABCpdf.ABCGecko NuGet package. Something like:

It took quite a while, and at the end, it showed me a message, saying that I need to manually (hate that word) copy a folder called XULRunner21_0 to the MVC project’s bin folder.

The Firefox / Gecko XULRunner Folder

The folder is needed for AbcPDF to connect to Firefox 21 (what’s used in v9, I guess it’s 38 in v10).

The folder, which has so many files and subfolders, was present in the root of my ASP.NET MVC project.

I didn’t want to have to commit this ~40 MB folder to our source control. The customer used NuGet package restore and didn’t want to keep binary files in source.

I know different people and different projects handle dependencies differently, and it can get interesting, but in my case, it was not wanted.

So, I modified the web project .csproj file, and added the following after a PostBuild <Task> in the file:

This made the folder show up in the project web project root in Visual Studio, and get copied to the bin folder, but the actual files were pulled from the package folder, not left in the website root itself.

The approach in general is very useful for adding an entire folder as a linked item in Visual Studio. I hope that little trick has helped!

Meligy’s AngularJS & Web Dev Goodies — Issue7: Goodbye 2014!

Here we go, it’s the last day of the year!

Hi, it’s Meligy from GuruStop.NET, and this is another issue of the AngularJS and web development newsletter.

I wrote this intro several times this month to fit the success of the first ng-sydney usergroup meeting, a company presentation I put online about Angular 2, Christmas holidays and gifts and all, my own dramas with the first MacbookPro I owned ever, and now, well, here it comes, on the last day of the year!

According to my records, there’re 60+ new subscribers to this newsletter since the last issue. Thanks a lot if you shared it with your friends, and if you are one of the new friends, make sure to check the previous issues at

If you are not, this is always your go-to reference in addition to searching your mailbox. And thanks for always being here at this end of the newsletter :)

It has been a few weeks since last issue, so, I’m making it up for you. This issue is going to be long. Let’s jump in quick:


Angular 2.0

Video: My Take on Angular 1.3+ (1.x) and Angular 2.0
In this ~17mins video I share a few ideas about the misconceptions people seem to have about Angular 2.0, and where Angular 1.x is going. You probably read a few of them in previous issues of the newsletter.

AngularJS 2.0 Status and Preview
A pretty nice writeup on the current status of Angular 2`.0 with code. It’s a bit long that the post offers a table of contents!

Angular 1.4

Video: AngularJS 1.4 Planning Meeting

If you are interested in knowing what’s likely to make it to Angular 1.4 and 1.5. 1.4 is likely to make it to ng-conf in late January 2015 BTW! InfoQ wrote an article closely related to this video focusing on what to expect beyond 1.4 for the 1.x in 2015.

Official Angular Blog: Planning Angular 1.4
The team also put a summary of the meeting in this blog post. One thing you want to look at is the “Progress” and “Design Doc” links in there for the real meat of what’s going on.

A couple interesting things about 1.4 are:

  • The router looks like it’ll have an appearance in this release. I personally doubt it’ll be good enough!
  • There’s another round of forms improvements. These are always welcome :)

Learning Angular 1.x Cheat Sheets is the best place for short videos teaching AngularJS. The creator of the site now has posted some cheat sheets targeting some very interesting areas of Angular:

  • AngularJS Core Services (PDF)
  • AngularJS Directive Definition Object (PDF)
  • AngularJS ui-router (PDF)

Creating Custom AngularJS Directives – 7 Part Article
A very detailed primer on creating directives from Dan Wahlin. Dan has popular courses on AngularJS, and more importantly he is the creator of the Angular in 60 minutes video, which I still consider the best intro video for developers new to AngularJS.

Getting Started with Angular and Accessibility
A good introduction to accessibility in AngularjS and the ngAria official AngularJS module.

Videos: “AngularJS Fan” YouTube channel
A very good collection of videos with nifty tips & tricks, They are all very short also like the awesome videos. I found this channel by accident via a video about Isolate-Scope Attribute Expressions Use Dependency-Injection In AngularJS.


An Introduction To Unit Testing In AngularJS Applications
This article takes a good angle at unit testing your application with both theory and code.

3rd Party Modules & Tools

A replacement for default cookies service in AngularJS to take away the limitations of the default cookie implementation.

A good tool whether you need to support custom languages or just add proper pluralization. It takes care of the obvious details like lazy loading and flexibility to replace parts of the library.

A collection of directives and services that seem interesting. You can check their table directive with support for serverside paging/sorting, their range filter for when you need to repeat on a range of numbers not really a list of objects. I saw it mentioned a few times but haven’t played with the code myself yet.

If you ever needed to create something like a constants.js file that had some values that don’t change in the life of the application but change per dev environment (local, test, stage, prod), you might find this useful (provided you use gulp too I guess).

Code To Read – The Web-based Markdown Editor
A very good Markdown editor built with AngularJS on the front and NodeJS ExpressJS on the backend. It offers offline storage support and integration with many cloud storage options (Dropbox, Google Drive, One Drive, Github). You can play with it at but I thought you might be more interested in checking the code ;)

John Papa AngularJS Styleguide
John Papa is another great speaker who is now focusing on AngularJS among other things. He created a very nice styleguide that is worth looking at and deciding for yourself what to agree and what to disagree with.
If you are into validating your coding style, you should also learn about the official angular-hint module.


Should I be learning ES6?
I think the answer is yes. ES 6 is still effectively JavaScript vNext, but it’s good to learn one of the trasncompilers to ES 5 (current JavaScript). However, this link is not about what I think, but what reddit thinks.

CSS And Preprocessors

Introducing Sass-Compatibility
SASS was created on top of Ruby. There are a few popular versions of it out there and there’s a C implementation as well that other platform implementations rely on. The Sass-Compatibility site helps you tell what features are incompatible with what implementation. I haven’t really fallen into this problem before, but I’m very aware it exists and it might be just a matter of time.

The 5 Most Popular Frontend Frameworks of 2014 Compared
I looked here to see if I missed anything, but, TBH it just felt like Bootstrap is the king of this area still, arguably of course.

HTML5 & Web Components

Web components allow you to create independent UI widget that can have their own HTML/CSS/JS includes and have some JS-rich behaviors. While browser support is still poor for web components, the Polymer project provides a great polyfill for current browsers.

Video Playlist: Polymer Tutorial
I was looking for some Polymer tutorials and found this playlist which has several videos with good introductions to the Polymer concepts

Video: Web Components and the Future of CSS
Another introduction video focusing on shadow DOM (DOM that has its own isolated CSS and DOM selection).

No more JS frameworks
The post talks about what feature are making it to standard / native technologies that we have always had to get a JavaScript framework to have, like async loaded HTML templates, JS promises, etc.

The State of HTML5 Gaming
An interesting comparison of the big JavaScript game engines out there.


Node.js Best Practices
It’s not very common to see good best-practices guidance in the NodeJS world, especially for those who don’t write a lot of NodeJS code, so this one is a good gem.

A book about one of the most important and often confusing topics of NodeJS. It’s written as a Markdown file on Github with a build tool to view in browser, a nice way!

Functional Programming

Video: Functional programming design patterns by Scott Wlaschin
My friend @JorgeFioranelli suggested this video as a great one for those interested in the topic in general (He is my go-to person on it).

Having further look I noticed the entire site is a collection of NDC videos. NDC is one of the best in-depth developer conferences I know of, so, you better browse the video listing for topics that may interest you.

Microsoft Technologies


Using AngularJS, ASP.NET MVC, WebAPI and EntityFramework to build NLayered SPA
A detailed code sample that features an interesting boilerplate template builder


Yeoman generators for ASP.NET 5
With official production support for Mac OS & Linux in next version, we get to see crazy things like yo aspnet! Not just that, it has sub-generators that correspond to Visual Studio’s Add-New-Item dialog feature as well: Adding New Items to Your ASP.NET 5 Project with Yeoman Subgenerators.

Video: ASP.NET 5 – What do you need to know
A good introduction to the upcoming version of ASP​.NET, from ALT​.NET Sydney usergroup.

Building future .NET projects is quite pleasant
While several resources focus on development experience in ASP​.NET 5, this article talks about how nice the CI build story is as well (using TeamCity as the build runner as well).

Internet Explorer

It’s still no Chrome for sure, but there’re good things happening with the automatically updating (AKA: ever-green) IE 11. Here’s one:


How To Migrate To HTTPS
Addy Osmani from Chrome team shared this guide for “gradually” migrating to HTTPS. It’s currently an 8 pages WIP document. Definitely worth checking.


Pakt Publishing $5 Ebooks Bazonga
Pakt are having a $5 sale on all their ebooks and videos. It will end very soon so use it quick if you will.

Principles of Distributed Computing (lecture collection)
Looking at what algorithms fit more in a distributed world.

JavaScript Books

Eloquent JavaScript And Other Books
A post on reddit about how good the book Eloquent JavaScript triggered a good discussion of other good JavaScript.

Programming JavaScript Applications
Another good JavaScript book available for read onlineASP​.NET


How to Be an Expert in a Changing World
To quote “When experts are wrong, it’s often because they’re experts on an earlier version of the world”.

How to Send Email Like a Startup
This is more for the engineers who sometimes have to write marketing emails, ones that maintain customer relationship not normal ones like this email or you internal company email. I find it a very good sill to learn these for everyone though.


This is a one off section that will not make a frequent appearance in this newsletter.

In the last newsletter I talked about the new ng-sydney usergroup for AngularJS developers in Sydney. I promised to share a picture from the first meetup. So here it is:

There were about 35+ people attending. We had an open talk session that I was worried could go wrong but people actually loved it that it went beyond time. It was a great night.


A quick mention of the actions I’d love you to do NOW before closing this message (before the end of the year):

  • Send me feedback about YOUR thoughts of the newsletter and how to improve it (just email me or reply to this email) – I promise I’ll take action!

  • And tweet the newsletter to your friends if you are on twitter (or share on Facebook, LinkedIn, G+, you have one of these, don’t you?)


Have a great 2015 everyone :)

What is the significance of ASP​.NET vNext? (Quick 6 points)

The Question:

This is a question I found recently on Quora:

What is the significance of ASP.NET vNext?

I do not have much info on the topic more than watching some relevant TechEd videos, etc, but I managed to provide an answer and thought it might be good material for a quick blog post:

The Answer

Several things:

  • Real cross OS support. Microsoft is testing it even under Mono on Mac OS.

  • Much lighter framework, meaning it’s faster, and can handle more requests per second using the same hardware

  • Highly imporved compilation speed and workflow. Speed is due to compiling in memory not to disk), this ends a real slow productivity killer in large projects, the workflow improves as developers just save a file, refresh the browser and get the changes just like in JavaScript, CSS, etc

  • New codebase, meaning less need to know which defaults you need to change to get the behavior of a version that fixes a bug in a previous version, more testing-friendly APIs, etc

  • Better Node.JS integration, allows ASP .NET developers to easily get access to JS tools available at Bower package manager for example

  • New and clean replacement of MSBUILD (for ASP .NET only), allowing developers to easily write tasks similar to grunt, etc instead of complex and limiting MSBUILD tasks.

More Info

The best resource for ASP.NET vNext is simply – you can also check this video linked from that page:

Allow Me To Share My Toolset Choices for Developing On .NET

There was a question in a tech facebook group I co-manage about what tools you’d use if starting a new project today.


I don’t know for sure. It depends -of course- is the expected answer. For example, there’s some idea I had I mind I considered using MongoDB or CouchDB for, while still using .NET, and then I wasn’t sure if I go extra mile in DB I’d go for Node or Rails as well or would prefer .NET for my personal productivity. I also often use Node/Bower when checking libraries with many dependencies.

So, for this question, I thought what tools I might use in a company project. Thinking back, I found that most tools I use now are good enough for what they do. So, I thought I’d list these.

These tools are my personal experience though. While some of them are widely adopted in Readify, some others may have been specific to some clients or Readify teams I worked with. Every team is free to choose the tools that work best for them and make it easier to deliver high quality deliverables in sensible time, so, even if you are at Readify, your mileage may vary…

The Tools

Server Side Web


  • SQL Server (or SQL Azure, although I don’t like SQL Azure, because it’s not compatible with some scripts generated from SSMS, which I sometimes use to generate migration scripts)

  • DbUp for DB migrations (there are some other nice options now)

  • Special SQL views + Web API OData + MS Excel for reporting

Client Side Web

  • Angular.JS on the client when I have the choice, Knockout.JS and jQuery UI (being deprecated now) at some big client I keep going back to every few gigs

  • LESS for CSS, or SASS (SCSS) when the CSS is handled by one of our favourite design agencies

  • Chrome devtools for web debugging (obviously), unless it’s IE issue of course.


  • Phonegap (most just the open source part of it, Cordova) and Ratchet CSS framework (considering alternatives, like TopCoat) for mobile development, with Angular.JS

  • Considering Xamarin as their work seems to be VERY cool, and I recently get access to their stuff via my company (OT: Also considering Neo4j DB for similar reasons).

IDEs and Text Editors



Internal Communication

  • Several kinds of wikis used by different clients, often with OneNote

  • HipChat for team communication, sometimes Skype and/or Lync as well

  • AnswerHub (Stackoverflow clone) for internal questions forum where I can safely quote client sensitive information in my question

  • Yammer for internal company social network

How about you?

What tools do you you use when developing?

Let me know in the comments, via email, or on twitter!

Enforcing ASP.NET MVC Conventions With Unit Tests, Or Solving The AJAX HTML Redirect To Login Page Problem

This blog post is about an ASP.NET MVC workaround we implemented in a previous project. We solved the problem by enforcing using a class that extends one of ASP.NET MVC classes, which in itself created another problem, as new developers joining the project may always use the old class. The solution to this problem was not something that I invented, but it’s also not a very common practice.

So, if you are interested, here’s the entire story…

Detecting Session Timeout In AJAX Requests

We wanted to solve a problem where in an AJAX heavy ASP.NET MVC application, if the user triggers an AJAX action after staying inactive for longer than our application timeout, the call to the controller action, which normally gets a JSON response, would instead get the HTML of the login page.

This is a known issue in ASP.NET (particularly System.Web). A feature that’s on by default is returning a redirect to the login page instead of a HTTP Unauthorized Status code (401). After the redirect the response returned is a successful (HTTP Status Code 200) load of the login page. That means even our Angular.JS error interceptors (or jQuery handlers, etc.) don’t notice there was an error.

A fix for this was turning this feature off. We inherited the Authorize attribute as below:

SuppressFormsAuthenticationRedirect is the property that disables the login redirect. Microsoft set it to false by default so that it’s backwards compatible.

ASP.NET MVC doesn’t recognize AJAX requests through Request.IsAjaxRequest() via Accept header or so. It does via checking X-Requested-With header. Most AJAX-capable frameworks like jQuery and others offer a way to intercept all requests and add extra headers, for example, in that app, we configure Angular.JS to include the header with some code similar to this:

Enforcing The Convention

The obvious problem with the previous solution is that we are ignoring The Power Of Defaults. Any other developer who may join the project needs to know that using Authorize is a no-no, and even for old devs (myself included),
it’s very easy to just forget and use Authorize not AuthorizeRedirect just out of habit.

Solving this problem was quite easy though, we added the following test to our Unit Tests project:

I hope the code is self explanatory. We check the web project assembly for all ASP.NET MVC Controllers, then we check the Controllers and all their Action methods for existence of the AuthorizeAttribute. We filter those that use the correct attribute (AuthorizeRedirectAttribute), and we Assert that there are no the no Controllers or action remaining, otherwise, we tell the developer which Controller or Action needs to be fixed, and how to fix it as well.

Room For Improvement

The drawback of this is that our Unit Test project had to reference the ASP.NET MVC assemblies and gets more stuff than most tests should need. We can overcome this by moving our “convention” tests into another project completely, but for this project the conventions were very few and it seemed fine.

Of course the same method can be applied to any other convention you enforce in your project. One obvious example is ensuring all Controllers inherit from a custom base Controller class instead of the ASP.NET MVC class directly. I know people who already do this, as I mentioned in the opening the technique is not new by any means, but it’s worth even more popularity.

Speaking of improvement, the code for this test class was optimized a bit while writing this blog post, there is always room for improvement :)


In case you were reading the code carefully, the IsNullOrEmpty() method I used in assertions is a custom extension method we had in the project, a very simple one as you may expect:

And That’s it!

I hope you found the technique useful if you haven’t used it before, or found the post a good place to reference it to those who didn’t.

Serializing A PagedList Using JSON.NET In ASP.NET MVC – Gotcha And Workaround

Recently I discovered that there’s no one standard way for AJAX-driven server-side paging in ASP.NET MVC (in Web API, you can expose an IQueryable). For the case in hand, I decided to use PagedList for the server bit of the game.


The PagedList interface looks a bit like this (for demonstration only, real code is a bit different, check its source code for the real stuff):

It provides nice properties for paging, and exposes itself as enumerable and has an indexer. Apart from this snippet, the library also provides an extension method ToPagedList() to apply to any enumerable and allow it to populate the properties from it (by enumerating on it, and by calling the Count() method).

We were also using JSON.NET for JavaScript serialization, which is pretty much defacto standard nowadays.

The JSON.NET Serialization Problem

JSON.NET has a nice implementation, if you serialize a class that implements IEnumerable<T>, and you don’t have a special treatment rule for it (via what JSON.NET calls “Converter” classes), when you serialize an instance of the class to JavaScript, it will be serialized as a JavaScript array, where the enumerated objects are the contents of this array. Makes lots of sense right?

Well, yes, except when you have a custom collection like PagedList, and you want to treat it as an object that has several properties, not as an array. JSON.NET does provide a solution for this actually, all you need to do is apply the [JsonObject] attribute to your class.

Unless you don’t own the source code of this class.

In this case, you need to inherit from it. By doing this, I lose the nice ToPagedList() extention method (because it creates an object of the PagedList class directly), but luckily it does nothing but calling new PagedList() with the parameters we give it, so, we don’t lose much.

Here’s how my implementation looks like:

Apart from having to copy the constructors to pass parameters to the base ones, have you noticed the extra Items property in there?

That’s because the Subset member it includes is actually a field, not a property, and JSON.NET won’t serialize that by default, I could override it somewhere else, but since I’m fiddling with this here, it made sense to just stick a property to the class.

Bonus: A Bit More On Implementation

In my actual code, I have added the Dynamic Linq NuGet package, and assumed a single property for sorting (which was fair for the situations where I intend to use this), so, I complemented the code above with another class that looks like this:

This allows the controller to instantiate an instance of the SerializablePagedList class, pass it all the way to whatever repository method I have.

The repository method will take it as a parameter, work out what IQueryable it needs, and instead of passing it to UI, it calls CreatePagedListFromQueryable(), which returns an innocent-looking PagedList object (because SerializablePagedList inherits PagedList) that the repository can pass back to the controller, which can serialize it to JavaScript without a problem, then the rest is all JavaScript code to work out how create the paging parameters, and how to use the returned paging hints.

Even more, now that I think about it, maybe I should change the return type to SerializablePagedList, to make the Items property visible to the developer (because they’d think it’s magic, and in coding, magic is BAD). I’ll leave this as an exercise for you :)

Final Words / Disclaimer

The motivation behind this post is that I found the problem of serializing PagedList using JSON.NET a challenge and I wanted to help others work it out faster than I did. Is this how I’d recommend doing paging? Well, I don’t know, but if it’s what you choose, I hope that I have saved you some time.

And more importantly, is it good enough to be the defacto standard I mentioned I was after in the beginning of the post? Not really. I think it’s not bad, but definitely not the best. I’d love to see less clever (read: hacky), and more simpler solutions.

Manually Compressing Any ASP.NET Page, PageMethod, MVC Action, HTTPHandler,..

Compressing A Single ASP.NET Response Manually

This post is about compressing your HTTP result without using IIS Dynamic Compression. I’ll save the story to the end and give you the code first:

Well, this shows how to do the compression itself. Depending on how you do ASP.NET, you probably will call it differently.

In my case, I called it manually from an ASP.NET Webforms PageMethod (more on why below), but if you are using ASP.NET MVC for example, you probably want to wrap it in an ActionFilter and apply that to the action you want to compress its output. Let me know in the comments or on twitter if you have a problem implementing it in a particular situation.

IIS Dynamic Compression

IIS 7+ has built in dynamic compression support (compressing output of server-side scripts like ASP.NET, PHP, etc.). It’s not by default because compressing dynamic content means running the compression for every request (because it doesn’t know what the server-side script will generate for every request, the point of using server-side programming is generating dynamic content!).

Static compression on the other side (caching static files like styles and scripts) is on by default because once the static resource is compressed, the compressed version is cached and served for every future request of the same file (unless the file changes of course).

General advice: I’d say if your server side scripts expect to return large text-based content (say, large data, even after paging, etc. like large reports or whatever), always turn dynamic compression on, at least for the pages that expect to return large data sets of text.

In many cases though the majority of large files will be scripts (and possibly images) will be the larger parts though, which are often taken care of (for scripts for example) by IIS static compression or ASP.NET Bundling.

Creating Explicit Route To Website Homepage In ASP.NET MVC

Typically, you have this standard piece of routing configuration:

Which does the job of matching “/” to HcomeController‘s Index action.

The reason it works is simple, the id parameter is obviously  optional, the action parameter if not present will be set to Index, so, this routing will match “/home/index/”, and similarly will match “/home/”. But the controller also will be set to HcomeControlimageler if it’s not present (the Controller suffix is a convention in class name), so, this matches “/home/” and “/”.

Using Explicit Route

Until here, there is no point of this blog post. So, lets say for whatever reason you are using other routing rules, because your desired routes don’t follow this very convention or because you don’t want to couple public URL structure to internal class names or have another reason to make your routes explicit, how do you set a route for the homepage or website root “~/” URL in this case?

One possible case is to have this exact default route still there, but make sure it’s at the very end of your route registrations, after all other have been registered, so, it has the least priority in matching. The drawback is that it’s still more generic than its purpose, technically allows using it for other actions than the one handling the homepage, and every request to homepage will go through all routes tried first (which is usually not a very slow thing to be honest).

So, a nicer way is to be able to have an explicit homepage route. Maybe even one that can be put on the top of route registrations to make the request to our homepage the fastest ever (although again, it’s not a big deal or difference, but nice to have). Turns out the way is VERY easy, just set the URL to an empty string “”.

Yeah, that’s it (the “name” doesn’t matter BTW, and you can obviously use whatever controller/action too). Even if you are using the default routes, you can combine it with them, and put it before them too. Empty string will NOT match any URL that is not empty (you can argue all other requests are matched against this, but comparing a string against an empty one must be VERY quick, right?)

Note that this all is application specific, so, the root here is website root “~/” not server root, so, this should still work if your website is hosted under some virtual directory too.


p>Not that it matters a lot, but thought some of you would be interested :).

Have fun.


Grouping ASP.NET MVC Controllers And Views By Features

If you don’t like your folders to be named after blah software pattern (that happens to be MVC), and would like instead of having “Views” and “Controllers” folders (not many use “Models” folder), to see things like “Administration”, “Members”, “FeatureA”, “FeatureB” etc. folders in your web application instead, it’s not that hard.

Putting Controllers Next To Their Views, Literally

The easiest (likely not most convenient) way to do this is to move your controller class files to their corresponding view folders! Controllers are picked up by ASP.NET MVC by base type and class naming convention, not location or filename, so you can put them anywhere in the project and they’ll still be picked up.

This is how it works for the default ASP.NET MVC 4 “Internet Website” template:


The obvious problem now is that it’s harder to find them. Depending on how you usually work, you can renamed the file to make it show first (Add a couple of underscores to it for example), or maybe it doesn’t make a difference at all if you locate files by CTRL+ , (comma) or CTRL+SHFIT+T (if you use Resharper).

I’m kind of with the 2nd option (leaving them as they are, and locating them using keyboard), especially that you usually shouldn’t have so many actions in your views, and not have have so many partials in the same folder anyway, so, even finding the controller in the Solution Explorer shouldn’t be a big problem (compare the “Home” controller ease to the ‘”Account” controller).

Replacing Views With Features

The first way still feels dirty, controllers in the “Views” folder? Isn’t “Views” part of the MVC pattern language also? Let’s rename that to “Features” (or whatever makes more sense to you). Then our application will look like:


But then we need to tell the RazorViewEngine to look for views in our new folder. There are several ways to do this, I’ll go for the stupid one for simplicity. In your ASP.NET MVC 4 global.asax.cs file, add the following to Application_Start:():


The code is very straight forward. We just replace the “Views” in what the engine looks for to be “Features”.

there is another place that we’ll still need to modify, the “_ViewStart.cshtml” file has the default Razor layout file set with full path, change it to:

Now the website should work fine.

Starting With Features

If you were to just add another folder called “Features” and under it add the various feature folders, each including the Controller and Views(s) used with it may (make more sense,, maybe even leave things like “Shared” in the original “Views:” folder and delete the “controllers” one),, these are the changes that would still be needed:

  • Manipulating the RazorViewEngine so that it looks for views in that features folder. Instead of replacing the existing entries, we insert new ones (copy existing ones to a List<string>, insert the new values at position 0 so that they are looked up first, and returning this as array to the view engine property).
  • Copying the “web.config” in the “Views” folder (not the one in the root of your web application) to your features folder
  • Copying the “_Appstart.cshtml” file from the “Views” folder to your features folder, as this is what provides common view initialization like setting the default layout file

Or Just Use Areas!


p>If all you really needed was grouping features, and you don’t mind the Controllers, and Views folders under each feature (or maybe even like them), then you could just use ASP.NET MVC Areas feature and have all the application features split in corresponding areas.

However, I assume if you really wanted just that, you wouldn’t be looking for this post anyway :-).


Yes, I know, there is still more bloat folders in the ASP.NET MVC application. Some of them you may (or may not) use like “Content” or “Scripts””, some of them maybe shouldn’t be there or should have been in a different project, but this just to show some of what can be done using the existing hooks, especially that using them didn’t turn to be that hard.