European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European Cloud ASP.NET MVC Hosting - Spain :: Pipeline in ASP.NET MVC

clock April 22, 2014 09:49 by author Scott

In this article, I will write simple tutorial about detail pipeline of ASP.NET MVC.

Routing

Routing is the first step in ASP.NET MVC pipeline. typically, it is a pattern matching system that matches the incoming request to the registered URL patterns in the Route Table.

The UrlRoutingModule(System.Web.Routing.UrlRoutingModule) is a class which matches an incoming HTTP request to a registered route pattern in the RouteTable(System.Web.Routing.RouteTable).

When ASP.NET MVC application starts at first time, it registers one or more patterns to the RouteTable to tell the routing system what to do with any requests that match these patterns. An application has only one RouteTable and this is setup in the Application_Start event of Global.asax of the application.

public class RouteConfig
   {
   public static void RegisterRoutes(RouteCollection routes)
   {
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

   routes.MapRoute(
   name: "Default",
   url: "{controller}/{action}/{id}",
   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );
   }
   }


protected void Application_Start()
{
   //Other code is removed for clarity
   RouteConfig.RegisterRoutes(RouteTable.Routes);
}

When the UrlRoutingModule finds a matching route within RouteCollection (RouteTable.Routes), it retrieves the IRouteHandler(System.Web.Mvc.IRouteHandler) instance(default is System.Web.MvcRouteHandler) for that route. From the route handler, the module gets an IHttpHandler(System.Web.IHttpHandler) instance(default is System.Web.MvcHandler).

public interface IrouteHandler
{
   IHttpHandler GetHttpHandler(RequestContext requestContext);
}

Controller Initialization

The MvcHandler initiates the real processing inside ASP.NET MVC pipeline by using ProcessRequest method. This method uses the IControllerFactory instance (default is System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.

protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
   SecurityUtil.ProcessInApplicationTrust(delegate {
   IController controller;
   IControllerFactory factory;
   this.ProcessRequestInit(httpContext, out controller, out factory);
   try
   {
   controller.Execute(this.RequestContext);
   }
   finally
   {
   factory.ReleaseController(controller);
   }
   });
}

Action Execution

1. When the controller is initialized, the controller calls its own InvokeAction() method by passing the details of the chosen action method. This is handled by the IActionInvoker.

public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)

2. After chosen of appropriate action method, model binders(default is System.Web.Mvc.DefaultModelBinder) retrieves the data from incoming HTTP request and do the data type conversion, data validation such as required or date format etc. and also take care of input values mapping to that action method parameters.

3. Authentication Filter was introduced with ASP.NET MVC5 that run prior to authorization filter. It is used to authenticate a user. Authentication filter process user credentials in the request and provide a corresponding principal. Prior to ASP.NET MVC5, you use authorization filter for authentication and authorization to a user.

By default, Authenticate attribute is used to perform Authentication. You can easily create your own custom authentication filter by implementing IAuthenticationFilter.

4. Authorization filter allow you to perform authorization process for an authenticated user. For example, Role based authorization for users to access resources.

By default, Authorize attribute is used to perform authorization. You can also make your own custom authorization filter by implementing IAuthorizationFilter.

5. Action filters are executed before(OnActionExecuting) and after(OnActionExecuted) an action is executed. IActionFilter interface provides you two methods OnActionExecuting and OnActionExecuted methods which will be executed before and after an action gets executed respectively. You can also make your own custom ActionFilters filter by implementing IActionFilter.

6. When action is executed, it process the user inputs with the help of model (Business Model or Data Model) and prepare Action Result.

Result Execution

1. Result filters are executed before(OnResultnExecuting) and after(OnResultExecuted) the ActionResult is executed. IResultFilter interface provides you two methods OnResultExecuting and OnResultExecuted methods which will be executed before and after an ActionResult gets executed respectively. You can also make your own custom ResultFilters filter by implementing IResultFilter.

2. Action Result is prepared by performing operations on user inputs with the help of BAL or DAL. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult.

3. Various Result type provided by the ASP.NET MVC can be categorized into two category- ViewResult type and NonViewResult type. The Result type which renders and returns an HTML page to the browser, falls into ViewResult category and other result type which returns only data either in text format, binary format or a JSON format, falls into NonViewResult category.

View Initialization and Rendering

1. ViewResult type i.e. view and partial view are represented by IView(System.Web.Mvc.IView) interface and rendered by the appropriate View Engine.

public interface Iview
{
  
void Render(ViewContext viewContext, TextWriter writer);
}

2. This process is handled by IViewEngine(System.Web.Mvc.IViewEngine) interface of the view engine. By default ASP.NET MVC provides WebForm and Razor view engines. You can also create your custom engine by using IViewEngine interface and can registered your custom view engine in to your Asp.Net MVC application as shown below:

protected void Application_Start()
{
  
//Remove All View Engine including Webform and Razor
   ViewEngines.Engines.Clear();
   //Register Your Custom View Engine
   ViewEngines.Engines.Add(new CustomViewEngine());
   //Other code is removed for clarity
}

3. Html Helpers are used to write input fields, create links based on the routes, AJAX-enabled forms, links and much more. Html Helpers are extension methods of the HtmlHelper class and can be further extended very easily. In more complex scenario, it might render a form with client side validation with the help of JavaScript or jQuery.



ASP.NET MVC Hosting - HostForLIFE.eu :: How to Localization URL With ASP.NET MVC 4 ?

clock February 21, 2014 09:52 by author Peter

To offer a website in multiple languages using ASP.NET MVC 4 , we simply need to add some resource.resx files to our project. Based on the language of the browser, IIS will match the localization resource. However, what if we want to give the choice to the user?

The goal

One pattern often used to achieve this, is to split the resource based on the URL. Example:
http://www.DomainName.com/EN/About for the English path
http://www.DomainName.com/FR/About for the French path

The needs

We will need something to grab the desired language from the URL and set it as the current language.

The Solution

First, let's add a new route. Asp.Net uses routing to parse the URL and to extract information from it, while keeping the displayed URL more user friendly. The default route is {controller}/{action}/{id}.

So without a new route, our language will be treated as a Controller name; but that’s no good.
The route we want is {lang}/{controller}/{action}/{id}. We could just replace the default, but then what would happen to "normal" calls?

The best thing to do is to add our localized route first and keep the default second. The way the routing works, it will use the first route that matches. Since we will use the two-letter code for chosen language, lets add the first part {lang}, which must be two characters long to be considered valid. You can see this in the code where I define a constraint using the following Regex: "^[a-zA-Z]{2}$".

Now that we have the language, we must change the user interface culture of the current thread. I decided to use an Attribute, making it easy to use. Under the Filter folder add a new class which inherits from ActionFilterAttribute. This method will check if "lang" is available from RouteData. If lang is present it will change the currentUICulture of the current thread. If "lang" is not part of the URL, then it will set it to the default.

We could put the [Localization] attribute on all controller classes, but a best practice is to create a BaseController class and use it there.

 

You can now change the language of the entire website by changing the URL.

Use it everywhere

To use it in the view and the controller it's easy; just add the namespace and just type Resources.NameOfYourResourceString.
To use it in the validation and the generated code from the model, we could use something like this:

This way, in the view, the code will still stay clean and simple.

@Html.LabelFor(model.UserName)



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in