Category Archives: ASP.NET MVC

ASP.NET Web API and Streaming Video Content

Below post explains how to stream video content through ASP.Net Web API’s, below is the code for Video Controller which inherits from API Controller. API show both GET and POST approaches.

Main thing to concentrate in the code is usage of Push Stream Content. PushStreamContent enables option to send data in small stream packets which then could be used on client side to stream videos, download large files etc.

    /// API Controller for streaming video files.
    public class VideoController : ApiController
        private const string videoFilePath = "~/Movies/";

        /// Gets the live video.
        public IHttpActionResult GetLiveVideo(string videoFileId, string fileName)
            string filePath = Path.Combine(HttpContext.Current.Server.MapPath(videoFilePath), fileName);
            return new VideoFileActionResult(filePath);

        /// Gets the live video using post.
        /// The request.
        public IHttpActionResult GetLiveVideoPost(VideoFileDownloadRequest request)
            string filePath = Path.Combine(HttpContext.Current.Server.MapPath(videoFilePath), request.FileName);
            return new VideoFileActionResult(filePath);

    /// Action Result for Returning Stream
    public class VideoFileActionResult : IHttpActionResult
        private const long BufferLength = 65536;
        public VideoFileActionResult(string videoFilePath)
            this.Filepath = videoFilePath;

        public string Filepath { get; private set; }

        public Task ExecuteAsync(CancellationToken cancellationToken)
            HttpResponseMessage response = new HttpResponseMessage();
            FileInfo fileInfo = new FileInfo(this.Filepath);
            long totalLength = fileInfo.Length;
            response.Content = new PushStreamContent((outputStream, httpContent, transportContext) =>
                    OnStreamConnected(outputStream, httpContent, transportContext);

            response.Content.Headers.ContentLength = totalLength;
            return Task.FromResult(response);

        private async void OnStreamConnected(Stream outputStream, HttpContent content, TransportContext context)
                var buffer = new byte[BufferLength];

                using (var nypdVideo = File.Open(this.Filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    var videoLength = (int)nypdVideo.Length;
                    var videoBytesRead = 1;

                    while (videoLength > 0 && videoBytesRead > 0)
                        videoBytesRead = nypdVideo.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, videoBytesRead);
                        videoLength -= videoBytesRead;
            catch (HttpException ex)
                // Close output stream as we are done


On the client side you can view the video file using below code snippet

<video width="480" height="320" controls="controls" autoplay="autoplay">
        <source src="api/video/live?videoFileId=1001&fileName=sampleVideo.mp4" type="video/mp4">

Attribute Routing in ASP.NET MVC

With earlier version of ASP.NET MVC routing was strictly convention based and there was no way to give custom routes for specific controller and action associated with it. With ASP.NET MVC 5 and above attribute based routing feature was introduced. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. The earlier style of routing, called convention-based routing, is still supported and you can combine both techniques in the same controller and web application as well. To enable attribute routing, call MapMvcAttributeRoutes during configuration in RouteConfig.cs file

public static void RegisterRoutes(RouteCollection routes)


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

Now in the controller as part of action we can declare custom routes for each and every action

public class HomeController : Controller
    public ActionResult Index()
        return View();

    public ActionResult About()
        ViewBag.Message = "Your application description page.";
        return View();

    public ActionResult Contact()
        ViewBag.Message = "Your contact page.";
        return View();

You can set a common prefix for an entire controller by using the [RoutePrefix] attribute like show below

public class HomeController : Controller
    public ActionResult Index()
        return View();

    public ActionResult About()
        ViewBag.Message = "Your application description page.";
        return View();

    public ActionResult Contact()
        ViewBag.Message = "Your contact page.";
        return View();

When to use Attribute Routing
The convention-based routing is complex to support certain URI patterns that are common in RESTful APIs. But by using attribute routing you can define these URI patterns very easily. For example, resources often contain child resources like Clients have orders, movies have actors, books have authors and so on. It’s natural to create URIs that reflects these relations like as: /clients/1/orders. This type of URI is difficult to create using convention-based routing. Although it can be done, the results don’t scale well if you have many controllers or resource types. With attribute routing, it’s pretty much easy to define a route for this URI.

Similar attribute routing concept holds good for Web API 2

Explain Model Binding in ASP.NET MVC ?

Suppose you had an API like shown below

public class Person
    public string FirstName { get; set; }
    public string Lastname { get; set; }
    public string Email { get; set; }
    public int Id { get; set; }
public class PersonController : Controller
    public ActionResult Update(Person person)
        //Do Some thing over here

You can easily post a Person to that action method using JSON through $ajax using jQuery. But the bigger question is how ASP.NET MVC transforms the JSON payload or forms payload to required object. Under the hood, ASP.NET MVC uses the DefaultModelBinder in combination with the JsonValueProviderFactory to bind that value.Then question arises Why simply deserialize the incoming JSON request directly to the model (Person)? There are couple of ways in which data gets posted

    • application/x-www-form-urlencoded – When you submit a typical HTML form, the content type of that submission is application/x-www-form-url-encoded. the contents of the form is posted as a set of name value pairs separated by ampersand characters. The name and value within each pair are separated by an equals sign. When content is posted in this format, the DefaultModelBinder calls into the FormValueProvider asking for a value for each property of the model
    • application/json – Another content type in which u can post data is through JSON objects like shown below
      <script type="text/javascript">
          $(function () {
              var person = { FirstName: "Aamol", LastName: "Gote", Email: "", Id: 1 }
              var personJSON = JSON.stringify(person);
                  url: '/Person/update',
                  type: 'POST',
                  dataType: 'json',
                  data: personJSON,
                  contentType: "application/json",

      When this code executes, notice that the content is encoded as JSON rather than form url encoded. JSON is a serialization format so it’s in theory possible that we could straight deserialize that post to a Person instance, but ASP.NET MVC does not do that, reason for it is has to perform validation on input values, if it does not then the serialization would fail. Serialization is an all or nothing affair, when serialization fails, all you know is that the format didn’t match the type. You don’t have access to the granular details we need to provide property level validation.

So to solve this we really want is a way bind each property of the model one at a time so we can determine which of the fields are valid and which ones are in error. Fortunately, the DefaultModelBinder already knows how to do that when working with the dictionary-like IValueProvider interface. All the ket value pairs form-encoded and JSON are coverted to type IValueProvider (Dictionary) and DefaultModelBinder already knows how to bind those values to a type while providing property level validation.
Value providers provide an abstraction over where values actually come from. Value providers are responsible for aggregating the values that are part of the current request, e.g. from Form collection, the query string, JSON, etc. They basically say “I don’t know what a ‘FirstName’ is for or what you can do with it, but if you ask me for a ‘FirstName’ I can give you what I have.”
Model binders are responsible for querying the value providers and building up objects based on those results. They basically say “I don’t know where directly to find a ‘FirstName’, ‘LastName’, or ‘Age’, but if the value provider is willing to give them to me then I can create a Person object from them.”

Model binders aren’t locked to individual sources they can build objects from an aggregate of sources for e.g. if you person object is posted and a client makes a JSON POST request to an action method with the url /person/update/1 with the following content:

{ FirstName: "Aamol", LastName: "Gote", Email: ""}

The DefaultModelBinder will pull the Id value from the RouteData and the FirstName, LastName and Email values from the JSON when building up the Person object. Afterwards, it’ll perform validation without having to know that the various values came from different sources.
In Summary – we use a value provider for JSON to enable property level validation of the incoming post and also so that model binding can build up an object by aggregating multiple sources of data without having to know anything about those sources.

Tech Interview App – Android Store – Try it and let me know Feedback…

Try my Android Store App – App Contains Categorized Q&A for tech categories focus on OSS stack (Angular, Node) for building hybrid apps as well as  MS Stack (.NET, ASP.NET, MVC, Web API…). Provides Question Count Statistics as well categorized question count break down. Questions and Answers periodically without app upgrade.

Tech Interview App

Android Store Listing

App is built using HTML 5, Angular JS and Web API in the back Ground.

Plan is to add Questions Weekly to the Respository and make more enhancements :).

1 2 3 4 5 6 7

Send Feedback…..

Viewbag, ViewData and Tempdata

ViewBag & ViewData
Helps to maintain data when you move from controller to view.
Used to pass data from controller to corresponding view.
Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
ViewData requires typecasting for complex data type and check for null values to avoid error.
ViewBag doesn’t require typecasting for complex data type.


TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. generally used to store only one time messages like error messages, validation messages.

Html.Partial and Html.RenderPartial Html.Action and Html.renderAction

Difference Html.Partial and Html.RenderPartial

While one can store the output of Html.Partial in a variable or return it from a method, one cannot do this with Html.RenderPartial. The result will be written to the Response stream during execution/evaluation.

Difference is Html.Partial returns an MvcHtmlString and  Html.RenderPartial outputs straight to the response.

Html.RenderPartial: directly render/write on output stream and returns void and it’s very fast in comparison to Html.Partial

You can store the output of Html.Partial in a variable, or return it from a function. You cannot do this with Html.RenderPartial. The result will be written to the Response stream during the execution

Difference Html.Action and Html.RenderAction

The same is true for Html.Action and Html.RenderAction.

The return type of Html.RenderAction is void that means it directly render the responses in View where return type of Html.Action is MvcHtmlString you can catch its render view in controller and modify it

ASP.NET MVC Request Life Cycle

1. ASP.NET framework is heart of ASP.NET MVC application. Basically, ASP.NET is a request processing engine. It takes incoming request as input and sends it through internal pipeline till the end point.
2. The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server.
3. In integrated mode in IIS 7.0, a unified pipeline handles all requests. When the integrated pipeline receives a request, the request passes through stages that are common to all requests. These stages are represented by the RequestNotification enumeration. All requests can be configured to take advantage of ASP.NET functionality, because that functionality is encapsulated in managed-code modules that have access to the request pipeline. For example, even though the .htm file-name extension is not explicitly mapped to ASP.NET, a request for an HTML page still invokes ASP.NET modules. This enables you to take advantage of ASP.NET authentication and authorization for all resources.

4. So whenever a request comes from Client to Server, it will hit HTTP.SYS First. Hypertext Transfer Protocol Stack (HTTP.sys)  – The HTTP listener is part of the networking subsystem of Windows operating systems, and it is implemented as a kernel-mode device driver called the HTTP protocol stack (HTTP.sys). HTTP.sys listens for HTTP requests from the network, passes the requests onto IIS for processing, and then returns processed responses to client browsers.

5. HTTP.SYS is Responsible for pass the request to particular Application pool. How HTTP.SYS comes to know where to send the request ?  This is not a random pickup. Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web application, it checks for the Application Pool and based on the application pool it send the request.

  • Application Pool:  Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availability for any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn’t not impact other web application as they they are configured into different application pools.
  • When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) .
  • Worker Process: :  Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.  All the ASP.Net functionality runs under the scope of worker process.  When a request comes to the server from a client worker process is responsible to generate the request and response. Worker Process loads up ASP.Net run time. Application domain is created.

4. After the application domain has been created and the HostingEnvironment object has been instantiated, application objects such as HttpContext, HttpRequest, and HttpResponse are created and initialized. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, which includes cookies and browser information. The HttpResponse object contains the response that is sent to the client, which includes all the rendered output and cookies.
5. After all application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class. It then uses the derived class to represent the application. An instance of the HttpApplication object is assigned to the request. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request.
6. For MVC application in Application_Start event for Global.ascx RegisterRoutes(RouteTable.Routes) API for RouteConfig is invoked.
7. Inside the RegisterRoutes we register route by giving: route name and constraints.
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”, action = “Contact”, id = UrlParameter.Optional }

8. The MapRoute is actually extension method in RouteCollectionExtensions.cs. Now, you can see how the route with particular URL is being register and associated with MvcRouteHandler.

9. Post this ASP.NET starts executing the HTTP Modules registered in the pipeline. In BeginProcessRequest there is a cycle that iterates all modules and execute each of it.
10. One of the module is UrlRoutingModule. The goal of this module is basically matching incoming request by URL with pre-defined Route configuration and return corresponding handler for this request.
11. HttpApplication calls the Init method for each of the registered modules. Init method has HttpApplication as parameter, in the Init method for Url Routing Module for the event handler PostResolveRequestCache of HttpApplication object it assigns the method PostResolveRequestCache Method within the routing module. When the HttpApplication event is fire the PostResolveRequestCache method of the UrlRouting Module gets fired. In this method following steps are performed
12. Match the request to defined route
13. For found matched Route it gets corresponding route handler (MvcRouteHandler). MvcRouteHandler was configured earlier in the application start.
14. Get HttpHandler method for the MvcRouteHandler is called which returns the instance of MvcHandler
15. This in turn calls the RemapHandler method in the HttpContext instance, to this method MvcHandler is passed. Remapahandler tells IIS which Httphandler we want to use.
16. Once handler has been set, handlers process request method is been called by ASP.Net framework.
17. We know that HttpHandlers are special objects that handles requests and produce a response. MvcHandler produce nothing by itself. Instead, it uses ControllerBuilder object for creating Controller and call controller Execute method. It is Execute method responsibility to find corresponding action, call action and wrap action return result it HTTP response
18. MVC handler supports both sync and async process request methods.
Sync Process Request
• It declares IController and IControllerFactory these are initialized in the ProcessRequestInit method. IControllerFactory instance is
initialized to DefaultControllerFactory and then the IControllerFactory instance calls the CreateController API which creates the appropriate
controller instance and is assigned to IController.
• Then the IController Execute method is invoked.

Async Process Request
• In async world the things are bit more complex. There are no one single method, but 2 instead. BeginProcessRequest and EndProcessRequest.
• The request initialization and creation of factory and controller is exactly the same. The difference in execution, for async controller 2
delegates are being created.
• Then Controller BeginExecute method is invoked.

19. In summary after the controller object is created using the controller factory following happens :
a. The Execute() method of the controllerbase is called
b. This Execute() method calls the ExecuteCore() method which is declared abstract and is defined by Controller class.
c. The Controller class’s implementation of the ExecuteCore() method retrieves the action name from the RouteData
d. ExecuteCore() method calls ActionInvoker’s InvokeAction() method.

20. Controller has following method which can be overridden and called in the same sequence
1. Initialize – Override to perform custom initialization before ControllerBase.Initialize sets Controller.ControllerContext with the encapsulated route data.
2. BeginExecuteCore
3. CreateTempDataProvider – Override to use a custom TempData provider. SessionStateTempDataProvider is used by default.
4. CreateActionInvoker – Override to use a custom action invoker. AsyncControllerActionInvoker is used by default
5. Controller then Invokes the Authentication Filters. Controller.OnAuthentication() API is invoked which then invokes the individual IAuthenticationFilters, prior to invoking filters it checks if the request I already authenticated if not then it invokes IAuthentication Filters. Use IAuthenticationFilter to authenticate a user action toward the intended resources. Authentication filters execute in order until one of the filters returns a non-null result.
6. Post Authentication Filters Controller invokes the Authorization filters. Controller.On Authorization() API is invoked which then invokes the individual IAuthorizationFilters, prior to invoking filters it checks if the authorization context existis if not then it invokes IAuthorization Filters. Use IAuthorizationFilters to authorize a user action toward the intended resources. Authorization filters execute in order until one of the filters returns a non-null result.
7. Then controller calls the InvokeAction method, this is where the action filters kick in. 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.
8. When action is executed, it process the user inputs with the help of model (Business Model or Data Model) and prepare Action Result.
9. Controller then Invokes the Controller.OnResultExecuting() API. Controller implements IResultFilter (by inheriting ActionFilterAttribute). OnResultExecuting methods are executed in order before the result is executed.
10. Post the the Controller.OnResultExecuting Result filters are kicked in. Result filters are executed before (OnResultExecuting) 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
11. Controller then executes the ActionResult.ExecuteResult() which prepares the return ActionResult.
a. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult. Various Result type provided by the ASP.NET MVC can be categorized into two category- ViewResult type and NonViewResult type.
b. 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.
c. ViewResult type i.e. view and partial view are represented by IView(System.Web.Mvc.IView) interface and rendered by the appropriate View Engine which is this case is Razor.
d. View generation and rendering is handled by IViewEngine (System.Web.Mvc.IViewEngine) interface of the view engine.
e. 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 start.
f. Since ViewResult is the most common type of ActionResult we will look into what happens if the the ExecuteResult() method of the ViewResult is called. Following happens after the ExecuteResult() method of ViewResult is called.
i. ExecuteResult of ViewResultBase is Invoked
ii. ViewResultBase calls the FindView of the ViewResult
iii. ViewResult returns the ViewEngineResult
iv. The Render() method of the ViewEngineResult is called to Render the view using the ViewEngine.
v. The response is returned to the client.

12. To summarize Filters associated with controllers, there are 5 types of filters, they are executed in below sequence
a. AuthenticationFilter – Executes after Controller.OnAuthentication.
b. AuthorizeFilter – Executes before other filter or action method
c. ActionFilter – Executes before and after action method
d. ResultFilter – Executes before and after action result
e. ExceptionFilter – Executes when action method, action result and other filter throws exception