Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Can you please explain in detail, the use of App_Start() folder in MVC4? I see that this folder is actually not available in previous versions of MVC. There are 5 files in this folder.

  1. AuthConfig
  2. BundleConfig,
  3. FilterConfig,
  4. RouteConfig,
  5. WebApiConfig.
like image 976
Harsha V Chunduri Avatar asked Nov 13 '13 09:11

Harsha V Chunduri


People also ask

What is the use of App_Start folder in MVC?

The App_Start folder of MVC application is used to contain the class files which are needed to be executed at the time the application starts. The classes like BundleConfig, FilterConfig, IdentityConfig, RouteConfig, and Startup. Auth etc. are stored within this folder.

What is the use of FilterConfig in MVC?

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

What is AuthConfig Cs in MVC?

When you create an MVC 4 web application with the Internet Application template, the project is created with a file named AuthConfig. cs in the App_Start folder. The AuthConfig file contains code to register clients for external authentication providers.

What is the use of RouteConfig Cs in ASP NET MVC?

Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig. cs file is used to set routing for the application.


2 Answers

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.

like image 83
Spock Avatar answered Sep 27 '22 20:09

Spock


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.

like image 21
Bhuwan Pandey Avatar answered Sep 27 '22 21:09

Bhuwan Pandey