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

StackOverflow https://stackoverflow.com/questions/19949709

  •  30-07-2022
  •  | 
  •  

Pergunta

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.
Foi útil?

Solução

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.

Outras dicas

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.

In the previous versions of MVC, we just have RegisterRoutes() method in global.asax file to configure the routing. MVC 4 has built in templates to develop mobile web applications, web apis(restful http services).so to configure the routings for all those template driven development ,we will be using the AuthConfig.cs(Authorization),BundleConfig.cs(web potimization),,FilterConfig.cs,RouteConfig.cs,WebApiConfig.cs(WEB API) files and they will be mainteained in App_start folder. Lets have a look at each those config.cs files. AuthConfig.cs - settings in this file allows you to login to ASP.NET MVC site using third party client credentials like fb account,google account,yahoo account etc..or you can register also. BundleConfig.cs: settings in this file allows to improve the performance of an applications using bundling... WebApiConfig: sets the routing settings for WEB API (Note:No action needed in url)

  • AuthConfi g.cs: Used to confi gure security settings, including sites for OAuth login.

  • BundleConfi g.cs: Used to register bundles used by the bundling and minifi cation system. Several bundles are added by default, including jQuery, jQueryUI, jQuery validation, Modernizr, and default CSS references.

  • FilterConfi g.cs: Unsurprisingly, this is used to register global MVC fi lters. The only fi lter registered by default is the HandleErrorAttribute, but this is a great place to put other fi lter registrations.

  • RouteConfi g.cs: Holds the granddaddy of the MVC confi g statements, Route confi guration.

  • WebApiConfi g.cs: Used to register Web API routes, as well as set any additional Web API confi guration settings.

All those settings are registered within the App_Start method of Global.asax.cs file

BundleConfig.cs:

This is used to create and register bundles for CS and JS files that we have in the template.

FilterConfig.cs- This is used to create and register global MVC filter error filter

RouteConfig.cs-

This is used to register various route patterns for your Asp.Net MVC application.

WebApiConfig.cs- This is used to register various WEB API routes like want login with credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google,

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top