Use of AuthConfig, BundleConfig, FilterConfig , RouteConfig and WebApiConfig in App_Start() folder in MVC

App_Start is just another folder that groups together ASP.NET MVC configuration, which in previous versions of ASP.NET MVC was done in Global.asax.

ASP.NET MVC introduces more and more configuration elements, and this folder is ideal to place this configuration. For example, MVC 5's new auth. configuration, such as for third-party login providers, are also placed within this folder (in Startup.Auth.cs).

App_Start is not a ASP.NET special folder recognized by ASP.NET/IIS. You can rename the folder if you want. The name is just a convention, like App_GlobalResouces etc.

Update:

Below are some information and reference points for each file. The use of these files are pretty straightforward. I have included few online references that might help your to understand more.

  • AuthConfig — registers external authentication providers. See ASP.NET MVC external authentication providers for more information.

  • BundleConfig — registers your CSS and JS so they can be bundled and minified. See also ASP.NET MVC: Guidance: Bundling and Minification.

  • WebApiConfig — only applicable if you are using Web API. It can be used to configure Web API-specific routes, any Web API settings and Web API services. See also configuring ASP.NET MVC Web API 2

  • FilterConfig — registered global filters. These filters are applied to all actions and controllers. See also ASP.NET MVC 3: Global action filters

  • RouteConfig — you already found information.


App_start folder has been introduced in Mvc4. It contains various configurations files like:

  • BundleConnfig.cs
  • FilterConfig.cs
  • RouteConfig.cs
  • WebApiConfig.cs
  • AuthConfig.cs

App_start is not a special folder in MVC nor the class files inside this, these are just normal class files with different application configurations(filtering, bundling, routing etc.) and all these settings gets registered within Application_Start method of Global.asax.cs file.


BundleConfig.cs:

This is used to create and register bundles for CSS and JS files. for eg. jQuery,jQueryUI,jQuery validation,Modernizr and Site CSS..

Bundling and minification are two techniques to improve request load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.) Microsoft provides assembly Microsoft.Web.Optimization for the same

for eg. Lets create two Bundles. one for style(css) and another for script(javascript)

You can create bundle for css and javascripts respectively by calling
BundleCollection class Add() method within BundleConfig.cs file.

STEP 1:

Creating Style Bundle

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));

Creating Script Bundle

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
 "~/Scripts/jquery-1.7.1.min.js",
 "~/Scripts/jquery.validate.min.js"));

STEP 2:

Above bundles are defined in BundleConfig class as:

public class BundleConfig
{
 public static void RegisterBundles(BundleCollection bundles)
 {
 //Adding StyleBundle to BundleCollection
 bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
 "~/Content/mystyle.min.css"));

 //Adding ScriptBundle to BundleCollection
 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
 "~/Scripts/jquery-1.7.1.min.js",
 "~/Scripts/jquery.validate.min.js"));
 }
} 

STEP 3:

Registering Bundle

All bundles are registered in the Application_Start event of Global.asax:

protected void Application_Start()
{
 BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Minification is a technique for removing unnecessary characters (like white space, newline, tab) and comments from the JavaScript and CSS files to reduce the size, in turn improve load time of a web page. for eg. jquery-1.7.1.min.js is the minified js file for jquery-1.7.1, mostly used for production environment, for non-prod you can better use non- minified js to have better readability.

for eg.

A Jquery function in uncompressed js may look something like:

( function( global, factory ) {

    "use strict";

    if ( typeof module === "object" && typeof module.exports === "object" ) {

        // For CommonJS and CommonJS-like environments where a proper `window`
        // is present, execute the factory and get jQuery.
        // For environments that do not have a `window` with a `document`
        // (such as Node.js), expose a factory as module.exports.
        // This accentuates the need for the creation of a real `window`.
        // e.g. var jQuery = require("jquery")(window);
        // See ticket #14549 for more info.
        module.exports = global.document ?
            factory( global, true ) :
            function( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            };
    } else {
        factory( global );
    }

same above function in compressed or minified js will look like:

!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}


FilterConfig.cs:

This is used to create and register global MVC filter:

for eg.

  • Authentication filters (Executed First)
  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters (Executed Last)

Note: As mentioned above Filters are executed in an order.

for eg. Authentication Filters introduced with MVC5:

 public interface IAuthenticationFilter
 {
  void OnAuthentication(AuthenticationContext filterContext); 
  void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
 }

You can create your CustomAuthentication filter attribute by implementing
IAuthenticationFilter as shown below-


  public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
  {
   public void OnAuthentication(AuthenticationContext filterContext)
   { 
    //logic goes here
   }

Runs after the OnAuthentication method

     public void OnAuthenticationChallenge(AuthenticationChallengeContext
 filterContext)
         {
            {  
              //logic goes here
             }
         }

Configuring Filters

You can configure your own custom filter into your application at following three levels:

Global level

By registering your filter into Application_Start event of Global.asax.cs file:

 protected void Application_Start()
 {
  FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 }

Controller level

By putting your filter on the top of the controller name:

 [Authorize(Roles="Admin")]
 public class AdminController : Controller
 {
  // Logic goes here
 }

Action level

By putting your filter on the top of the action name:

 public class UserController : Controller
 {
  [Authorize(Users="User1,User2")]
  public ActionResult LinkLogin(string provider)
  {
  // Logic goes here
  return View();
  }
 }

RouteConfig.cs:

This is used to register various route patterns for your Asp.Net MVC
application. Routing plays an important role in an ASP.NET MVC Application execution flow, it maps request URL to a specific controller action using a Routing Table. We can define Routing Rules for the engine, so that it can map > incoming URLs to appropriate controller. Routing Engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of corresponding controller. We can find the following piece of code > in Application_Start() method of Global.asax file.

protected void Application_Start()
     {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes); 
        BundleConfig.RegisterBundles(BundleTable.Bundles);
     }

We can find RouteConfig.cs file under App_Start folder. If we follow this method in RouteConfig class, we will find one default configured route as follows. Line 3 to 7 is configuring one default route.

public static void RegisterRoutes(RouteCollection routes)
{
1.   routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
2.
3.  routes.MapRoute(
4.      name: “Default”,
5.      url: “{controller}/{action}/{id}”,
6.      defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
7.      );
}

Line 4 : Name for the route. Line 5 : represent URL : Controller, action followed by id (if any). Line 6 : default controller will be Home, default action will be Index and Id is optional.


WebApiConfig.cs:

This is used to register various WEB API routes like as Asp.Net MVC, as well as set any addtional WEB API configurations settings.

AuthConfig.cs:

Used to register external authentication providers for eg. if you want to enable users to log in with credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google, and then integrate some of the functionality from those providers into your web application.


App_start folder has been introduced in Mvc4. It contains various configurations files like as :

  • BundleConnfig.cs,
  • FilterConfig.cs,
  • RouteConfig.cs,
  • WebApiConfig.cs

for you application.All those settings are registered within App_Start method of Global.asax.cs file

BundleConfig.cs:

This is used to create and register bundles for CS and JS files.By default various bundles are added in this file including jQuery,jQueryUI,jQuery validation,Modernizer and Site Css..

FilterConfig.cs-

This is used to create and register global MVC filter error filter,action filter etc.By default it contains HandleErrorAttribute filter.

RouteConfig.cs-

This is used to register various route patterns for your Asp.Net MVC application. By default,one route is registered here named as Default Route.

WebApiConfig.cs-

This is used to register various WEB API routes like as Asp.Net MVC,as well as set any additional WEB API configurations settings.