• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms
Showing posts with label Asp.Net MVC. Show all posts
Showing posts with label Asp.Net MVC. Show all posts

Wednesday, August 23, 2017

Comparison Between HttpModule and HttpContext

 Abhishek Tomer     August 23, 2017     .Net, Asp.Net, Asp.Net MVC     No comments   

Hi friends! Today we are going to list some of the differences between HttpModule and HttpContext.

Many of my developer friends are confused about HttpModule and HttpContext.
So, Today i am writing this post to help them as well as for the newbies that are starting learning Asp.Net.

So, Let's start with the definition of each.

HttpModule:
Let’s first understand what is HttpModule.It is a.NET Framework class that implements the IHttpModule interface. This is used as filters in IIS these modules filter data or the context inside the request. Every ASP.NET applications uses numerous system modules by default.

HttpContext:
This class implements IServiceProvider interface explicitly. Whenever any new request or response is made HttpContext object is created. This holds all information about the request.

Common things Between HttpModule and HttpContext:
HttpModule and HttpContext work in correspondence with each other in order to serve a module. HttpModule provides information about the user to the UserInfo object. This object is contained inside HttpContext which in turn read this information. HttpModules can start functioning before any other event starts.This provides HttpModule an advantage over MVC request response cycle because using this one can perform various tasks earlier to MVC framework.
HttpModule and HttpContext in Asp.Net
HttpModules and HttpContext
Comparing HttpHandlers and HttpModules
  • Multiple HttpModules can act upon a single request whereas, single HttpHandler can act on a single request only.
  • HttpModules can manipulate the request using various services whereas purpose of using HttpHandlers is to frame response which will be given back to the browser.
  • HttpModules are implemented through IHttpModule interface, and HttpHandlers are implemented through IHttpHandler interface.
  • There is one similarity in both HttpModule and HttpHandler. They both can registered using coding in or using config file.
  • HttpModules can hook up with any MVC lifecycle event but HttpHandler act on events specifically related to mapping and execution only.
MVCRouteHandler and MVCHandler
UrlRouting module is a unique module which contains PostResolveRequestCache event. Purpose of this event is matching of all of the request to the routing table. It executes a RoutingHandler for all of the mappings done by it. RoutingHandler is nothing but a class, which implements IRouteHandler interface. One method of this class is exposed which is named as GetHttpHandler.

This method returns the corresponding MvcHandler (a standard httphandler) for further execution. This uses two methods-
  1. IsReusable
  2. ProcessRequest
Summary:
So, Guys this is all about HttpModule and HttpContext in Asp.Net MVC.

I Hope in this post covered all the points about HttpModule and HttpContext in Asp.Net MVC which will be helpful to understand the concept of HttpModule and HttpContext in Asp.Net MVC.

Please share this post with your friends and colleagues.
For any queries please post a comment below.

Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Sunday, August 20, 2017

Filters in ASP.Net MVC

 Abhishek Tomer     August 20, 2017     .Net, Asp.Net MVC, Filters     6 comments   

Hi friends! Today we are going to discuss about using a very important feature of MVC i.e.“Filters“.

Filters are a unique feature of Asp.Net MVC which are used to inject custom logic before or after the action methods. The filters provide usability to analyse, verify and use data or actions of application in MVC. Knowledge of filters can help you greatly in writing logic before or after execution of MVC request life cycle events. This logic can control the execution or even restrict further execution of events.

Let's understand this with a simple example.

Whenever any request from a user is made, it is processed and the corresponding controller action provides requested view as a response to the user. Suppose, we need some extra processing in between this request- response cycle.
For example, verification of role of the user. In this situation filters are used to insert extra logic in between the request response cycle.

There are 5 types of filters in MVC5.
Filter in Asp.net MVC
Filter in Asp.net MVC
Now, Let's discuss each one of them in details.

Authentication filters:
Authentication filters are added features in MVC 5. These filters are executed in first place in request life cycle methods. These filter perform the authentication based on the logic.

Authorization filters:
Authorization filters are the second filter types to be executed. This filter executes after authentication filters successfully authorize roles to different users. This filters ensure that the current user is authorized to access the resources or not.

Action filters:
After authorization filters comes the time for execution of action filters. These filters simply execute the piece of logic before and after execution of controller methods.

Result filters:
Result filters are executed before and after result execution.

Exception filters:
As the name denotes, Exception filters are executed if any exception occurs while processing the request.
Diagram below will help you understand the sequence of execution of filters.
Action Method Execution process in MVC
Action Method Execution process

It's clear from the above diagram that as the controller executes, the filters, (Authentication and authorization) are triggered at very first. After this the model binding is done. Out of two IActionFilter interface methods the first one that is, “OnActionExecuting” is fired before execution of the action and the second one “OnActionExecuted“ is fired after the action execution.

At the last, there are result filters which are executed. Again, this filter implements two interface methods from IResultFilter interface. At first “OnResultExecuting” which is fired before the execution of the result, while “OnResultExecuted“ is fired after is fired after the action execution.

Exception filter is fired in those cases when exception is thrown. Here we can write our custom logic either to record exceptions as log or redirect to any error page.

Filters in Action:
Like any other life cycle events of MVC, implementing filters in MVC is very easy.

Authentication Filter:
The very first one in the queue is the Authentication Filter, which is added recently in MVC5. This filter gives us maximum benefits and can be used for all authentication related exercise. As we know,after URL routing, controller gets initialized and authentication filters comes in picture.

This filter implements IAuthenticationFilter interface as well as FilterAttribute base class. IAuthenticationFilter interface has got two methods, OnAuthentication and OnAuthenticationChallenge. OnAuthentication is mostly used for any type of authentication that is understood by our application including setting of identity Principle.

Now comes OnAuthenticationChallenge which gets executed before result execution. The result might require some checks to authorize users and identify unauthorise users in case of a HttpUnauthorisedResult case. Here OnAuthenticationChallenge is used to perform this check by adding some “challenge” to the result before it is sent to users.

How to implement??

Code:
using System.Web.Mvc.Filters;
using FilterAttribute = System.Web.Mvc.FilterAttribute;
namespace MvcFilters.CustomFilters
{
    public class AuthenticationFilter : FilterAttribute, IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            Utils.SessionManager.StoreInSession(filterContext, "OnAuthentication");
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            Utils.SessionManager.StoreInSession(filterContext, "OnAuthenticationChallenge");
        }
    }
}

As you must be wondering about the use of “StoreInSession” method call. So let’s clear it that these methods are just used to log all events in the session so that we could see the result at last.

Action Filters:
Action Filters require implementation of IActionFilter interface and FilterAttribute base class. The IActionFilter interface executes two methods namely OnActionExecuting which is executed before action method execution and OnActionExecuted which is executed after the action method execution.

Code:
using System.Web.Mvc;
using FilterAttribute = System.Web.Mvc.FilterAttribute;
using IActionFilter = System.Web.Mvc.IActionFilter;
namespace MvcFilters.CustomFilters
{
    public class ActionFilter : FilterAttribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            Utils.SessionManager.StoreInSession(filterContext, "OnActionExecuted");
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Utils.SessionManager.StoreInSession(filterContext, "OnActionExecuting");
        }
    }
}

Authorization Filter:
Authorization filter performs all necessary duties required for authentication process has been in use for performing authentication before the authentication filters. It implements IAuthorizationFilter interface and derive from FilterAttribute base class. The interface IAuthorizeFilter gives you one method to implement, “OnAuthorization” where you can perform authorization related checks.

Code:
using System.Web.Mvc;
using FilterAttribute = System.Web.Mvc.FilterAttribute;
using IAuthorizationFilter = System.Web.Mvc.IAuthorizationFilter;

namespace MvcFilters.CustomFilters
{
    public class AuthorizationFilter : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            Utils.SessionManager.StoreInSession(filterContext, "OnAuthorization");
        }
    }
}

Result Filter:
Result filter are the filters that gets executed before and after executing result to a particular http request. These filters perform checks and manipulate result before it is sent to the browser. The result filter implements IResultFilter interface and derives from FilterAttribute class.

Code:
using System.Web.Mvc;
using FilterAttribute = System.Web.Mvc.FilterAttribute;
using IResultFilter = System.Web.Mvc.IResultFilter;
namespace MvcFilters.CustomFilters
{
    public class ResultFilter : FilterAttribute, IResultFilter
    {
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            Utils.SessionManager.StoreInSession(filterContext, "OnResultExecuted");
        }

        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            Utils.SessionManager.StoreInSession(filterContext, "OnResultExecuting");
        }
    }
}

Exception Filter:
Exception filters are those filters which occur in case of exception in request execution. It can be customized as per the developer’s requirement to either create a log or send user to a different error page. This filter implement IExceptionFilter and derive from FilterAttribute base class.

Code:
using System.Web.Mvc;
using FilterAttribute = System.Web.Mvc.FilterAttribute;
using IExceptionFilter = System.Web.Mvc.IExceptionFilter;
namespace MvcFilters.CustomFilters
{
    public class ExceptionFilter : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            Utils.SessionManager.StoreInSession(filterContext, "OnException");
        }
    }
}

Finally, when customization of all filters is done its required to inform MVC to use them and this is done by registering filters. You must be wondering here that you have already used interfaces to implement filters but let me tell you it is not enough.

Registration of filters is done in following ways-

  • We can put them on controller or action methods as attributes.
  • We can also register them globally. Here it is not needed to put filters specifically on action or controller methods. 
This is done by registering filters in Application_Start event in Global.asax file. See the example below.

using MvcFilters.CustomFilters;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MvcFilters
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalFilters.Filters.Add(new AuthenticationFilter());
            GlobalFilters.Filters.Add(new AuthorizationFilter());
            GlobalFilters.Filters.Add(new ActionFilter());
            GlobalFilters.Filters.Add(new ResultFilter());
            GlobalFilters.Filters.Add(new ExceptionFilter());
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

In the given source code we have implemented all filters and created a log in the session. That is why we are able to see the execution order of all filters.
The output clearly shows the execution order of the filters in application. We can see that the first filter executed is OnAuthentication, after that OnAuthorization, then ActionFitlers (OnActionExecuting and OnActionExecuted). This is followed by OnAuthenticationChallenge. Now, comes the number of ResultFilters. We cannot see OnResultExecuted as it is fired after result is sent back to the browser.
Filters execution list
Filters Execution List
Summary:
So, Guys this is all about Filters in Asp.Net MVC.
I Hope in this post I have covered all the points about filters which will be helpful to understand the concept of Filters in Asp.Net MVC.

Please share this post with your friends and colleagues.
For any queries please post a comment below.

Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Sunday, August 6, 2017

Application Life cycle of Asp.Net MVC

 Abhishek Tomer     August 06, 2017     Asp.Net, Asp.Net MVC     2 comments   

Today i am going to tell you the Application life cycle of an Asp.Net MVC Application, this post is important for those who are new to Asp.Net MVC or want to refresh their knowledge about the application life cycle.

In today's world many of the developers doesn't know about how the application executes or how the requests and responses are handled by the application.

In this article your all concepts will get cleared and if you think that i have left something to mention in this post then please comment below so that i can update this post and help you.

So let's start now.

Any web application has two main application execution steps that events that are associated with start and end events of the application. Application start initiates when the application is executed for the very first time. Application end event is fired when application has been shut down.

It’s important to understand Web application life cycle events to get a better understanding on how ASP.NET MVC life cycle starts. In our last article of page lifecycle of Asp.Net MVC we have learned about the URL routing is the starting point for MVC application that has a collection of predefined routes to map from.

Note : URL routing handler gets this information from Application start event. These events are registered in Global.asax file which contains all the application level events. All the Application level Events are handled by Global.asax file.

Application_Start event is:
  • An event that fires when first request is received.
  • Can be used to run initial configuration and settings code.
  • The event takes care of registering all areas of MVC application, installing global filters, adding routes and bundles.
As I have mentioned Application_Start is the first event that gets called when the application is requested for the very first time, all the pre-application tasks like routing takes place here.

As you can see in the diagram below ResolveRequestCache needs to know the routes to choose from, and this needs to have static route collection that are already been created.
Request lifecycle of Asp.Net MVC
Request lifecycle of Asp.Net MVC
PreApplicationStart:
It is another option at the assembly level to register something before the application starts. It could be used to run some initial configuration code or register modules or any other code that needs to be executed before the application starts.

HttpHandlers:
These are the classes that implement IHttpHandler and generate a response to HttpRequest. There could be httpHandler re-assignment in a life cycle of a request but only one httpHandler executes and provides response at a time.

There are two sets of events in the Asp.Net MVC  page request life cycle that concerns HttpHandlers, (MapRequestHandler and PostMapRequestHandler) and (RequestHandlerExecute and PostRequestHandlerExecute).

MapRequestHandler and PostMapRequestHandler are the events in the life cycle which determines the httpHandler responsible for executing the request. Only the selection happens during this time.

RequestHandlerExecute and PostRequestHandlerExecute are the life cycle events that actually executes the htttp handler determined in the earlier phases of request life cycle.
HttpHandler in Asp.Net MVC Request life cycle
HttpHandler in Asp.Net MVC Request life cycle
Creating an HttpHandler:
  • Create a class that implements IHttpHandler interface
  • Register the HttpHandler through code or web.config
IHttpHandler exposes two members:
  1. IsReusable
  2. ProcessRequest()
DemoHandler.cs Code:
public class DemoHandler : IHttpHandler
    {
        public bool IsReusable { get { return false; } }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write("This is the DemoHandler");
        }
    }

HttpModules:
These are classes the that implements IHttpModule interface and are designed to respond to Life cycle events. In a given Http life cycle, multiple Http modules can respond to one single request and can also hook into multiple life cycle events. So they are not tied to any specific event, rather they can act at several places during the life cycle and expose multiple development possibilities.

One of the advantage of HttpModules is that it bring in the reusability, modules written once can be reused any several application across frameworks. Features such as logging and authentication are best examples of wrapping things up in a HttpModule.

Note : One can also do the all these things possible in HttpModule in a Global.asax file, but that won’t achieve reusability and abstraction.

Creating a HttpModule
  • Implement the IHttpModule interface
  • Register the HttpModule through code or web.config
IHttpModule exposes two members:
  1. Init()
  2. Dispose()
Summary:
Thats all about the Application Life cycle of Asp.Net MVC.
in our next session we will be learning differences between HttpModule and HttpContext.

I hope you have enjoyed this post.
Please share this post with your friends and colleagues to help them clearing the interview.

For any queries please post a comment below.

Happy Coding ðŸ˜‰
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Friday, July 28, 2017

ASP.NET State Management

 Abhishek Tomer     July 28, 2017     Asp.Net, Asp.Net MVC     4 comments   

State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in the application. Because a web applications are stateless means on each page posted to the server, the state of controls is lost.

Why we need of ASP.NET State Management
As we know that A Web Applications work on HTTP protocol and a HTTP protocol is a stateless protocol, meaning it does not retain state between client server requests. That’s we need to prevent store the state of an Asp.Net controls, web page information, object/data, and user in the application on each request response.

Example: - When we fill a registration form as a customer on an E-commerce Side and submit the button then we can see that all the value of text box are blanked automatically because when a client (your browser) submit the form then it send the request to server and server send back the response to that client between this communication all information associated with the page and the controls on the page would be lost with each round trip. Suppose a user filed the form but some field of form is not filed and hit submit button then all information of all filed are lost and user need to filed all information again. To retain the page state Microsoft provide the different technique to maintain or store the state of the page or application until user session end.

ASP.NET provides us with 2 ways to manage the state of an application.

Client Side State management Techniques
  • View State
  • Hidden field
  • Query Strings
  • Cookies
Server Side State management Techniques
  • Application State
  • Session State
ASP.NET State Management
Client Side Sate management: -
Client Side State management Techniques: - This technique is used to maintain or store the information on client machine (Web Browser).

There are following technique to use for Client Side State management.
(1) ViewState: - ViewState can be used to maintain the State of page information at page level. The term "Page Level" means that the information is being stored for a specific page and until that specific page is active (i.e. the page which is being currently viewed by the user). Once the user is re-directed or goes to some other page, the information stored in the View State gets lost. By default each Asp.Net control have EnableViewState=True. But can also disable the EnableViewState property at server control, page and configuration file level by setting the EnableViewState=False property.

Note: When an Asp.net web page rendered on browser then View State value is stored in a hidden field as Hashed Format on the page.

To set A value in ViewState Variable
ViewState[“Key”]=”Your value”;
To Get A value in ViewSate Variable
String Name= ViewState[“Key”].ToString();
Use: -  This is useful to retain the textbox value when post back event fired.or to retains a variable value in code behind because it is accessible on a single page.

(2) Hidden Filed: - Hidden Filed is same as view sate but it can be used in different style and hidden filed value is not visible to end user when page rendered.
int newVal = Convert.ToInt32(HiddenField1.Value) + 1;
HiddenField1.Value = newVal.ToString(); 
Label2.Text = HiddenField1.Value; 
Use: - If you want to store a user id in hidden filed when end user edit the from because we do not want to edit the user id by end user and during save the form we can get value from that hidden field. Hidden filed is not visible to end user.
Query String: - Query String can be used to send information from one page to other page from the URL.

Send UserID value by Query String from PageA To PageB
Response.Redirect(“/PageB?UserID=100);
Receive UserID value by Query String from PageB URL
Var QueryStringvalue=Request.QueryString[“UserID”];
Server Side Sate management: -
This technique is used to maintain or store the information on web server or SQL server database.
There are two type of technique use to maintain the session state
  • Application State
  • Session State
Application State
Application object is used to store the information globally across entire application and shared across multiple user sessions. Application State object are like multi-user global data.

Set value to Application Object
Application["GlobalVariable"] = 0;
Get value from Application Object
Lable1.Text= Application["GlobalVariable"];
Some Key Points
  1. Application State variables are stored on the web server.
  2. Application State variables are cleared, only when the process hosting the application is       restarted, that is when the application ends.
  3. Application State variables are not shared across a Web Farm or a Web Garden.
  4. Application state variables are not thread safe. Lock and Unlock methods of the application class must be used to protect against race conditions, deadlocks, and access violations.
    Application.Lock();
    Application["GlobalVariable"] = (int)Application["GlobalVariable"] + 1;
    Application.UnLock();
    
  5. Use application state variables only, when the variables need to have global access and when you need them for entire time, during the life time of an application. Cache object, can be used, as an alternative, if you need to have global access for a certain duration.
Application events in ASP.NET
Following event present in Global.asax.cs file.

Application_start: The Application_Start event is fired when a user hit application name on URL. Note  this event is fired only first time for one user.
void Application_Start(object sender, EventArgs e)
{
    Application["CountNumberOfVisitor"] = 0;
}
Application_Error: It is fired when an unhandled exception occurs in whole application, we can manage exception handling globally by this event.

Application_End: The Application_End event is raised just before an application domain ends because of any reason, it may IIS server restarting or making some changes in an application cycle or global configuration files.

Use:-
  1. Find the total number of visitor globally.
  2. Handel the whole application exception globally.
Session Sate
Application object is used to store the information across all pages, but only for a given single session. Session variables are like single-user global data.

Generally session is used to store user's information that is uniquely identify on browser. The server maintains the state of user information by using a session ID. When users send a request to server without a session ID then server creates a session ID for that request and sends back to client with every request and response to the same user.
So by this session ID a user can identify on the web application.

Set value to Session Object
Session ["GlobalVariable"] = 0;
Get value from Session Object
Lable1.Text= Session["GlobalVariable"];
Session Events in ASP.NET
Session_Start: The Session_start event is fired every time a new user makes a request without a session ID, i.e., new browser accesses the application, then a session_start event raised. Let's see the Global.asax file.
void Session_Start(object sender, EventArgs e)
{
   Session["ShoppingCartCount"] = 0;  // Code that runs when a new session is started
}
Session_End: The Session_End event is fired when session ends either because of a session time out expiry or explicitly by using Session.Abandon(). The Session_End event is fired only in the case of In proc mode not in the state server and SQL Server modes.

There are four session storage mechanisms provided by ASP.NET

In Proc mode:- In proc mode is the default mode and session values are stored in the web server's memory (in IIS). If there are more than one IIS servers then session values are stored in each server separately on which request has been made by client. Since the session values are stored in server, whenever server is restarted the session values will be lost. Default session time out is 20 min

 
In State Server mode:- In this mode session values store session in the web server process that is called as asp.net state service. This process is different from the asp.net worker process. The asp.net state service can be present on a web server or a dedicated machine before or after restart the web server.
Note: - To Start ASP.NET State Service we need to type services.msc in CMD windows and click OK. And right clicked on Start ASP.NET State Service and click start.
Advantages
  1. Session value is present until or unless server restart .
  2. We can be used with web farms and web gardens.
  3. State server provide more scalability than InProc.
Disadvantages
  1. StateServer is slower than InProc
  2. Complex objects, need to be serialized and deserialized
  3. If the StateServer, is on a dedicated machine, and if the server goes down all the sessions are lost.
In SQL Server mode: In this mode session values store in the SQL server process database. On each request and response.
  • Following step to configure asp.net web application to use SQLServer mode:
  1. Create the ASPState database using aspnet_regsql.exe tool.
    Type cd C:\Windows\Microsoft.NET\Framework64\v5.0.30319 in command prompt in my case I have use dot net framework v5 and press enter
  2. Type - aspnet_regsql.exe -S SQLServerName -E -ssadd -sstype p
  3. Press Enter. At this point you should have ASPState Database added.
  4. For help running this tool
    Visit at:  http://msdn.microsoft.com/en-us/library/ms229862(v=vs.100).aspx
  • Set the Session state mode=SQLServer and sqlConnectionString
        For windows authentication

        
         For sql serevr authentication

         
Advantages
  1. SQL Server is the most reliable option because it is survives worker process recycling and SQL Server restarts.
  2. It can be used with web farms and web gardens.
  3. It is more scalable than State server and InProc session state modes.
Disadvantages
  1. Slower than StateServer and InProc session state modes
  2. Complex objects, need to be serialized and deserialized
Note:
Web Garden - Web application deployed on a server with multiple processors
Web Farm - Web application deployed on multiple server

Cookie less sessions
As we know that By default sessions use cookies and session-id is stored as a cookie on the client computer which is provided by server when user send the request first time and session-id is used to identify if the request is coming from the same user or a different user.
Cookie less session mainly used if a user disabled the cookies from his or her browser and if we user the session variable to manage the user then sessions may not work as expected.
We can reduce this problem by setting cookieless="true" in web configuration file as:

For Set the cookieless session to true

After setting this we can see that session ID present of URL with question mark and used to each request and response.

Summary:
So, Guys this is all about State Management in Asp.Net.
I Hope in this post I have covered all the points about State Management which will be helpful to understand the concept of Maintaining state of your Application.

Please share this post with your friends and colleagues.
For any queries please post a comment below.

Happy Coding ðŸ˜‰
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Wednesday, July 19, 2017

Implementing basic authentication in ASP NET Web API

 Abhishek Tomer     July 19, 2017     Asp.Net, Asp.Net MVC, Web API     1 comment   

Overview:
In this post I am going to explain to how to implement basic authentication using custom authentication filter. Here am not using any membership technique like asp.net identity. Here I have created our own database that contains UserMaster table and Employee table.

There are following steps to achieve our goal
  1. Create a database that have user related information like UserName and Password in my case i have used following tables show below as:
  2. Create a new Blank Project named as BacisAuthentication
  3. Add an empty Asp.net Web API Project with No Authentication Mode selected from templates named as Demo.API
  4. Add a console application for data named as Demo.Data that contains two folders like Repository and Entity.
  5. Install the Entity Framework in both project. 
  6. Add the EDMX files in Entity folder and select both table.

    Implementing basic authentication in ASP NET Web API
    Entities in EntityFramework(EDMX) Diagram

  7. Create UserRepository Class and Add the following code as
  8. using Demo.Data.Entity;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Demo.Data.Repository
    {
        public class UserRepository
        {
            //Initialize the db context
            private DemoContext _Context;
            public UserRepository()
            {
                //Creating the db context object
                _Context = new DemoContext();
            }
    
            //Validate User by user name and passord
            public bool ValidateUser(string userName,string Password)
            {
    
                var result= _Context.UserMasters.SingleOrDefault(x => x.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase) && x.Password==Password);
    
                return result!=null?true:false;
            }
        }
    }
    
  9. Create EmployeeRepository for get the employee related data from database as:
  10. using Demo.Data.Entity;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Demo.Data.Repository
    {
        public class EmployeeRepository
        {
            //Initialize the db context
            private DemoContext _Context;
            public EmployeeRepository()
            {
                //Creating the db context object
                _Context = new DemoContext();
            }
    
            public List GetAll()
            {
                return _Context.Employees.ToList();
            }
            public Employee GetByID(int ID)
            {
                return _Context.Employees.Find(ID);
            }
        }
    }
    
  11. Adding the reference of Demo.Data project to Demo.API project.
  12. Create a Customer Filter for user authentication. here we need to create our custom authentication filter by creating a class BacisAthentication in model and implement the AuthorizationFilterAttribute. Complete code is given below.
  13. using Demo.Data.Repository;
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Security.Principal;
    using System.Text;
    using System.Threading;
    using System.Web.Http.Controllers;
    using System.Web.Http.Filters;
    
    namespace Demo.API.Models
    {
        public class BacisAthentication:AuthorizationFilterAttribute
        {
            public override void OnAuthorization(HttpActionContext actionContext)
            {
                //Check client passed any value in header or not
                if (actionContext.Request.Headers.Authorization == null)
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
                else
                {
                    //Get the Hear values
                    string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
                    //Decoded the authenticationToken values becouse client passed the user namd and password in encoded form
                    string decodedAuthenticationToken =Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
                    //Split the user name and password by : because client passed the user name and password as"userNameValue:Passwordvalue"
                    string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
                    string username = usernamePasswordArray[0];
                    string password = usernamePasswordArray[1];
                    UserRepository _userRepository = new UserRepository();
    
                    //validate from the database for this user name or passrod.
                    if (_userRepository.ValidateUser(username, password))
                    {
                        Thread.CurrentPrincipal = new GenericPrincipal(newGenericIdentity(username), null);                   
                    }
                    else
                    {
                        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                    }
                }
            }
        }
    }
    
  14. Now need to create a employee controller in controller folder and use the BasicAuthentication filter on each employee service. Means that if user is authenticated then we provide the service otherwise not. The following controller code is
  15. using Demo.API.Models;
    using Demo.Data.Entity;
    using Demo.Data.Repository;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    namespace Demo.API.Controllers
    {
        public class EmployeeController : ApiController
        {
            private EmployeeRepository emp = new EmployeeRepository();
            // GET api/Employee
            [BacisAthentication]
            public IEnumerable<Employee> Get()
            {
                return emp.GetAll();
            }
    
            // GET api/Employee/5
            [BacisAthentication]
            public Employee Get(int id)
            {
                return emp.GetByID(id);
            }      
        }
    }
    
  16. Now test the api by passing the user name and password in encoded formate in header with basic.
You can encode the username:password here
https://www.base64encode.org/
before encode
userName1:Password1
after encoded
dXNlcjE6cGFzd29yZDE=
In Header You need to select or write Authorization in key and in value section pass encoded value with basic example : basicdXNlcjE6cGFzd29yZDE=
Implementing basic authentication in ASP NET Web API
Example for Testing API

Summary:
So, Guys This concludes the concept of achieving authentication in ASP NET Web API.
I Hope this post will be helpful to understand the concept of Asp.Net Web API.

Please share this post with your friends and colleagues.
For any queries please post a comment below.

Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Tuesday, July 18, 2017

Page Life cycle of Asp.Net MVC

 Abhishek Tomer     July 18, 2017     Asp.Net, Asp.Net MVC, C#     1 comment   

In this article I am going to explain what exactly happens in ASP.NET MVC request life cycle and what each step in the life cycle does and how we can leverage it further based on our needs. This article specifically targets Page life cycle which is different from Application life cycle. A typical Application life cycle contains Application start and Application End events, however http Life cycle is something which is repeated for every request. Since application events are also part of life cycle, we will see them as we move along.

The MVC Request Life Cycle
The entry point of MVC Request life cycle is URL Routing module, the incoming request from IIS pipeline is handed over to URL Routing module which analyses the request and looks up Routing table to figure out which controller the incoming request maps to.


"Routing Table is a static container of routes defined in MVC application with corresponding controller action mapping. If the route is found in the routing table MVCRouteHandler executes and brings the instance of MVCHttpHandler".


Together they act as a gateway into the MVC Framework. MVC handler begins initializing and executing controller. The MVCHttpHandler also takes of converting route data into concrete controller that is capable of serving the request. MVC handler does all this with the help of MVC Controller factory and activator which are responsible for creating an instance of the controller. This is also the place where the Dependency Injection is performed if the application has been designed to invoke parameterized controller constructor and satisfy its dependencies.


After the controller instance is created the next major step is to find and execute the corresponding action. A component called ActionInvoker finds and executes the action defined in routing table. Before the action method is called model bindings takes place which maps data from http request to action method parameters. After the model binding, action filters are invoked which includes OnActionExecuting filter. This is followed by action execution and Action Executed filter execution and finally preparing Action Result.

Once the Action method has been finished executing the next step is Result execution. MVC separates the action declaration from Result execution. If the Result from action execution is view, then depending upon configuration, ASPX or Razor view engine will be called to find and render the html view as a response of http request. If the result was not view then it’s passed as-is to http response.

Following is the conceptual view of MVC request life cycle.
Page Life cycle of Asp.Net MVC
Page Life cycle of Asp.Net MVC

WebForms vs MVC
If you have ever developer a web forms application, then this is important scenario to understand about the difference between both.

  • In Web forms life cycle, service corresponds to the physical file. However in MVC, this concept is completely different as Controller Actions are executed to render a view to the view.
  • Inspite of having the differences, both Web forms and MVC requests are implemented through HttpHandler. In web forms each page is derived from IHttpHandler interface and request is served more directly. MVC controllers are also derived from HttpHandlers. From a higher level, MVC is just another way to manage request from ASP.net platform.
"One can create their own pipeline and build a framework like MVC or web forms on their own."
Pipeline for Asp.Net MVC Application
Pipeline for .Net Application

There are five main steps that happen when you make a request from an ASP.NET MVC website.
  1. Route Table Execution
  2. When application is run first time Application_Start method is called which is present under Global.asax file. Application Start method that registered the Route Table. A Route Table is a collection type that contains all the routes which are defined under the routeConfig files.
    public static void RegisterRoutes(RouteCollection routes)
     {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute("Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
     }

  3. UrlRoutingModule Intercepts the Request
  4. When first request made hit on browser URL then The UrlRoutingModule intercepts every request and find the correct route data. If UrlRoutingModule gets correct RouteData, it creates RequestContext object and forwards corresponding IRouteHandler(default id MvcHandler)

  5. MvcHandler Execution
  6. MvcHandler is responsible for initiate actual processing of ongoing request and generate response. MvcHandler gets information of current request through RequestContext object and passed to its constructor.

  7. Controller Execution
  8. MvcHandler uses the IControllerFactory instance and tries to get a IController instance. All Mvc controllers implement IController interface. This interface has Execute method which actually execute your action method code. So Mvc Controller executes the method from IController interface.

  9. Action Execution
  10. When a particular controller gets instantiated ActionInvoker determines which specific Action method needs to be execute. ActionInvoker uses ActionNameSelectorAttribute and ActionMethodSelectorAttribute to select Action method for execution.

    When an action method return the ActionResult then execution pipeline selects appropriate ViewEngine to render ViewResult that is taken care by view engine's interface IViewEngine. ASP.NET MVC has Webform and Razor view engines. We can also create our custom view engines.
Summary:
So, Guys This concludes the MVC request life cycle.

I Hope in this post I have covered all the points about MVC request life cycle which will be helpful to understand the concept of Asp.Net MVC request life cycle.

Please share this post with your friends and colleagues.

For any queries please post a comment below.

Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape