Process Flow of Single and Multitenancy ASP.NET MVC Application | ASP.NET MVC Tutorial

Single-Tenancy Application
The steps that lead from a user entering a website address in his browser to viewing the content are fairly straightforward. The browser sends a request for the content at that address to a server. The server receives the request, matches the address with an application, and passes the request on to that application for processing. The application reads the request, creates a response, and passes the response back to the server. The server returns the response to the browser and the browser presents the response content to the user. This is sometimes referred to as a single tenant application architecture. Each client application is matched with a single IP address and host name so that, as requests come in, the server can route them to the appropriate application (Figure 1).

Simplifying AccountController by Removing External Login Related Actions | ASP.NET MVC Tutorial

There are a number of methods on AccountController related to External Logins. If you examine AccountController carefully, you can go through and delete the code for the following actions:
  • Dissociate()
  • ExternalLogin()
  • ExternalLoginCallback()
  • LinkLogin()
  • LinkLoginCallback()
  • ExternalLoginConfirmation()
  • ExternalLoginFailure()
  • RemoveAccountList()
Additionally, there is a code #region for helpers. From here, we can delete the following items:
  • The member constant XsrfKey
  • The entire class ChallengeResult
At this point, we can also right-click in the code file and select Remove and Sort Usings to clear out unused namespaces

Delete External Login Related Views:
Along with the unnecessary Controller methods we just removed, we can also remove the unnecessary views related to external logins. If we open the Views => Account folder in Solution Explorer, we find we can delete the highlighted views below from our project:

How to Convert Synchronous ASP.NET MVC Action to Asynchronous ASP.NET MVC Action | Asynchronous Support in ASP.NET MVC Controller | ASP.NET MVC Tutorial

In ASP.NET MVC controller action method receives data from a web request and passes the data to a view which then creates the HTML to be sent to the browser. Frequently the action method needs to get data from a database or web service in order to display it in a web page or to save data entered in a web page. In those scenarios it's easy to make the action method asynchronous: instead of returning an ActionResult object, you return Task<ActionResult> and mark the method with the async keyword. Inside the method, when a line of code kicks off an operation that involves wait time, you mark it with the await keyword.
Here is a simple action method that calls a repository method for a database query:
public ActionResult Index()
    string currentUser = User.Identity.Name;
    var result = fixItRepository.FindOpenTasksByOwner(currentUser);

    return View(result);
And here is the same method that handles the database call asynchronously:
public async Task<ActionResult> Index()
    string currentUser = User.Identity.Name;
    var result = await fixItRepository.FindOpenTasksByOwnerAsync(currentUser);

    return View(result);
Under the covers the compiler generates the appropriate asynchronous code. When the application makes the call toFindTaskByIdAsync, ASP.NET makes the FindTask request and then unwinds the worker thread and makes it available to process another request. When the FindTask request is done, a thread is restarted to continue processing the code that comes after that call. During the interim between when the FindTask request is initiated and when the data is returned, you have a thread available to do useful work which otherwise would be tied up waiting for the response.

Generating Unique Token in C# | Generating Unique Token that Expires after 24 Hours in C# | C# Tutorial

There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.
To create a unique token:
string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
Basic example of creating a unique token containing a time stamp:
byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());
To decode the token to get the creation time:
byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24)) {
  // too old
Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.

Creating Cookie in ASP.NET MVC Action | Handling Cookies in ASP.NET MVC | Set Cookie Expiry in ASP.NET MVC | ASP.NET MVC Tutorial

We can create Cookie and set value to it in ASP.NET MVC Action method using the HttpCookie object using System.Web namespace. This created cookie should be added to HttpResponse object before returning the view in ASP.NET MVC Action method.

Below sample C# code demonstrated on how to create and set cookie in ASP.NET MVC Action method and pass it to Razor:

public ActionResult Index()
   HttpCookie cookie = new HttpCookie("cookie_name","cookie_value");
   cookie.Expires = DateTime.Now.AddDays(1);
   return View();
In detail:

To get a cookie:
HttpCookie cookie = HttpContext.Request.Cookies.Get("cookie_name");
To check for a cookie's existence:
HttpContext.Request.Cookies["cookie_name"] != null
To save a cookie:
HttpCookie cookie = new HttpCookie("cookie_name");
HttpContext.Response.SetCookie(cookie );

Route Constraints Supported in Attribute Routing in ASP.NET MVC 5 | ASP.NET MVC Tutorial

Route constraints let you restrict how the parameters in the route template are matched. The general syntax is {parameter:constraint}. The following table lists the constraints that are supported in Attribute Routing in ASP.NET MVC 5
alpha Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z) {x:alpha}
bool Matches a Boolean value. {x:bool}
datetime Matches a DateTime value. {x:datetime}
decimal Matches a decimal value. {x:decimal}
double Matches a 64-bit floating-point value. {x:double}
float Matches a 32-bit floating-point value. {x:float}
guid Matches a GUID value. {x:guid}
int Matches a 32-bit integer value. {x:int}
length Matches a string with the specified length or within a specified range of lengths. {x:length(6)}
long Matches a 64-bit integer value. {x:long}
max Matches an integer with a maximum value. {x:max(10)}
maxlength Matches a string with a maximum length. {x:maxlength(10)}
min Matches an integer with a minimum value. {x:min(10)}
minlength Matches a string with a minimum length. {x:minlength(10)}
range Matches an integer within a range of values. {x:range(10,50)}
regex Matches a regular expression. {x:regex(^\d{3}-\d{3}-\d{4}$)}

Applying Styles to @Html.TextboxFor in ASP.NET MVC | ASP.NET MVC Tutorial

We can Apply CSS class to @Html.TextboxFor in ASP.NET MVC. An overload of the TextBoxFor method allows you to pass an object for the HTML attributes as given below:

@Html.TextBoxFor(m => m.EmployeeName, new { Class="YourBackgroundClass" })
Then you can have a CSS rule such as:
.YourBackgroundClass { background:#cccccc; }
If you want to apply a style directly you can do:
@Html.TextBoxFor(m => m.EmployeeName, new { Style="background:#cccccc;" })

Allowing HTML Tags in TextBox in ASP.NET MVC | Allow HTML Tags in Form Post in ASP.NET MVC | ASP.NET MVC Tutorial

Request validation is a feature in ASP.NET that examines an HTTP request and determines whether it contains potentially dangerous content. In this context, potentially dangerous content is any HTML markup or JavaScript code in the body, header, query string, or cookies of the request. ASP.NET performs this check because markup or code in the URL query string, cookies, or posted form values might have been added for malicious purposes.

You can disable request validation for an entire application, but doing so is not recommended. To disable request validation in an ASP.NET MVC application, you must change request validation to occur earlier in the sequence of request processing. In the Web.config file, make the following setting:

  <httpRuntime requestValidationMode="2.0" />
  <httpRuntime requestValidationMode="2.0" />
In ASP.NET MVC, you can disable request validation for an action method, for a property, or for a field (input element) in a request. If you disable validation for an action method, you disable it for any requests that invoke that method—that is, all user input is allowed for any request that calls the action method. This approach is therefore the least secure way to disable request validation.

public ActionResult Edit(string comment)
    if (ModelState.IsValid)
        //  Etc.
    return View(comment);
If you disable validation for a property, you allow user input for any reference to that property. To disable request validation for a specific property, mark the property definition with the AllowHtml attribute:

public string Property1 { get;  set; }

Learn to Deploy Windows Azure Websites | ASP.NET MVC Windows Azure Video Tutorial

, ,
In this video tutorial, Scott Hanselman demonstrates creating an Azure Web Site and deploying Azure Web Site all from within Visual Studio 2013 using the new Azure SDK 2.2. Also, he attaches the debugger to the Azure Web Site in Azure itself!

What is HATEOAS, REST, and Hypermedia? | ASP.NET MVC, ASP.NET Web API, Azure Video Tutorial

, , ,
Scott Hanselman and Mat Velloso talks about REST and RESTful Web Services. Also discusses about HATEOAS, which actually means "Hypermedia as the Engine of Application State." Scott talks to Mat Velloso about all these topics and get s a nice primer on REST as it relates to hosting Web Services in the Azure Cloud.

What is Routing in ASP.NET MVC? | ASP.NET MVC Interview Question | ASP.NET MVC Programmer Guide

, ,
In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file. ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but are not mapped to physical files.

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define routing rules for the engine, so that it can map incoming request URLs to appropriate controller.

Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses “go” button, 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.

Designing Richer Applications using ASP.NET MVC | ASP.NET MVC VIdeo Tutorial | ASP.NET MVC Programmer Guide

This video tutorial would target how can we leverage the benefits of ASP.NET MVC4 to create a clean designed web application and customize it's user interface to work on mobiles with jQuery Mobile.

Because of widespread use of mobile smartphones and gaining popularity of tablets, web applications for the mobile platforms have to be pleasant and user-friendly. You can always create native applications for mobiles, but native application development requires platform specific skill-sets and code. When applications have to be scaled , upgrading multiple code bases is time-consuming and costly. Hence the need of hour is to have a single solution that targets multiple platforms .

ASP.NET MVC 4 with its new set of features enables websites to be adaptive across different mobile platforms. But there is no point for this technology to work hard in battle of maintaining user interfaces for the mobiles. To accompany we have to rope in its best friend jQuery Mobile.

ASP.NET MVC4 and jQuery Mobile together create stunning applications for desktop and mobile platforms using single code-base. Our aim of targeting multiple platforms with single solution is fulfilled by these two folks who love to mix and match user interface with stylesheets and javascripts and create platform independent applications.

OWIN OAuth Components in ASP.NET MVC Application | ASP.NET MVC Tutorial | ASP.NET MVC Application

OAuth middleware consists of several components that work together to complete the OAuth process. The following classes are used to configure and register the middleware, instantiate the provider, and handle authentication. Each component is described below in the order they are required by the authentication process.


An authentication extensions class is used to create an API used for registering the middleware with the OWIN pipeline. The class Custom AuthenticationExtensions extends the IAppBuilder by providing a UseCustomAuthentication method. The U seCustom Authentication method gives other developers an easy to use API for initializing the middleware and its options while registering the middleware with Katana.


CustomAuthentication Options specifies configuration for the authentication process and objects used throughout the authentication process. This includes service endpoints and API parameters such as client ID and client secret. CustomAuthentication Options inherits from the AuthenticationOptions base class. The authentication options associated with a custom middleware are often referenced by other components asTOptions .


CustomAuthenticationMiddleware inherits from AuthenticationMiddleware < TOptions > where TOptions isCustomAuthenticationOptions CustomAuthenticationMiddleware initializes theCustomAuthenticationProvider , CustomAuthenticationHandler , and ILogger <CustomAuthenticationMiddleware > The AuthenticationMiddleware itself is rather sparse because most of the work has been abstracted away into the AuthenticationHandler .


Custom AuthenticationProvider specifies the delegates that are called during authentication. OnAuthenticatedis invoked when a user is successfully authenticated. OnReturnEndpoint , is invoked before the ClaimsIdentity is saved and the browser redirects to the originally requested URL.

Authenticated Context

CustomAuthenticationContenxt inherits from BaseContext . The AuthenticationContext receives and parses the user information retrieved from the authentication service. The AuthenticationContext properties contain the login session information as well as details about the user that logged in including the ClaimsIdentity andAuthenticationProperties .


CustomReturnEndpointContext inherits from ReturnEndpointContext ReturnEndpointContext provides information about the OWIN context and holds the authentication ticket information.


The CustomAuthenticationHandler is responsible for the bulk of the authentication process.CustomAuthenticationHandler inherits from AuthenticationHandler < CustomAuthenticationOptions > and has three methods that need to be overridden: AuthenticateCoreAsync ApplyResponseChallengeAsync andInvokeAsync .


This method is invoked during an HTTP response. The method will look for a response that requires authentication (401 unauthorized) and a matching authentication type. When this criteria is met the method will be responsible for creating the CSFR token and redirecting the browser to the authentication endpoint.


The InvokeAsync method is used to detect a callback request from the authentication service. InvokeAsync will check the request for a path that matches callback path (ex: /signin-facebook). When the callback path is detected the method will invoke AuthenticateAsyncCore via AuthenticateAsnyc Once AuthenticateAsyncCore is complete the method will create a ReturnEndpointContext , grant the ClaimsIdentity and complete the request by redirecting to the application’s ExternalLoginCallback action.


AuthenticateCoreAsync performs several tasks. The method will validate the CSRF token insuring the security of the request. Next, the access token is request from the authentication service and if needed a second request is made for additional user information. Once the user’s information is collected the authentication context andClaimsIdentity are generated. Finally, the OnAuthenticated method is called and given theAuthenticationContext .

Diagrammatic Representation of ASP.NET MVC Authentication Process | Workflow of ASP.NET MVC OAuth | ASP.NET MVC Tutorial | ASP.NET MVC Programmer Guide

The below diagram shows the authentication process in ASP.NET MVC application. This diagram provides the complete workflow of OAuth in ASP.NET MVC

Explain Types of Data Used with ASP.NET Identity? | Expain about the Tables Generated for ASP.NET Identity | ASP.NET MVC Interview Question | ASP.NET MVC Programmer Guide

Below table provides details on types of data used with ASP.NET Identity:
UsersRegistered users of your web site. Includes the user Id and user name. Might include a hashed password if users log in with credentials that are specific to your site (rather than using credentials from an external site like Facebook), and security stamp to indicate whether anything has changed in the user credentials. Might also include email address, phone number, whether two factor authentication is enabled, the current number of failed logins, and whether an account has been locked.
User ClaimsA set of statements (or claims) about the user that represent the user's identity. Can enable greater expression of the user's identity than can be achieved through roles.
User LoginsInformation about the external authentication provider (like Facebook) to use when logging in a user.
RolesAuthorization groups for your site. Includes the role Id and role name (like "Admin" or "Employee").