Srinivas Interviews
Srinivas Interviews
All rights reserved. No part of this book can be reproduced or stored in any retrieval system, or transmitted in
any form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning
without the prior written permission of the author.
The author of this book has tried his best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author will
not be liable for any damages, incidental or consequential caused directly or indirectly by this book. Further,
readers should be aware that the websites or reference links listed in this book may have changed or
disappeared between when this book was written and when it is read.
All other trademarks referred to in this book are the property of their respective owners.
Dedication
My mother Mrs. Vriksha Devi and my wife Reshu Chauhan deserve to have theirs name on the cover as
much as I do for all theirs support made this possible. I would like to say thanks to all my family
members Virendra Singh(father), Jaishree and Jyoti(sisters), Saksham(son), friends, to you and to
readers or followers of my blog www.dotnet-tricks.com to encourage me to write this book.
-Shailendra Chauhan
Introduction
Writing a book has never been an easy task. It takes a great effort, patience and consistency with strong
determination to complete it. Also, one should have a depth knowledge over the subject is going to write.
So, what where my qualification to write this book? My qualification and inspiration come from my enthusiasm
for and the experience with the technology and from my analytic and initiative nature. Being software analyst,
consultant and blogger, I have through knowledge and understandings of .NET technologies. My inspiration and
knowledge has also come from many years of my working experience and research over it.
So, the next question is who this book is for? This book covers useful Interview Questions and Answers on
ASP.NET MVC. This book is appropriate for novice as well as for senior level professionals who wants to
strengthen their skills before appearing for an interview on ASP.NET MVC. This book is equally helpful to
sharpen their programming skills and understanding ASP.NET MVC in a short time.
This book is not only the ASP.NET MVC interview book but it is more than that. This book helps you to get the
depth knowledge of ASP.NET MVC with a simple and elegant way. This book is updated to latest version of
ASP.NET MVC5 and ASP.NET WEB API2.
I hope you will enjoy this book and find it useful. At the same time I also encourage you to become a continue
reader of the blog www.dotnet-tricks.com and be the part of the discussion. But most importantly practice a lot
and enjoy the technology. That’s what it’s all about.
To get the latest information on ASP.NET MVC, I encourage you to follow the official Microsoft ASP.NET
community website at www.asp.net. I also encourage you to subscribe to my blog at www.dotnet-tricks.com
that contains .NET, C#, ASP.NET MVC, EF, jQuery and many more tips, tricks and tutorials.
Shailendra Chauhan
Works as Software Analyst at reputed MNC and has more than 5 years of
hand over Microsoft .NET technologies. He is a .NET Consultant, founder
and chief editor of www.dotnet-tricks.com and
www.dotnetinterviewtricks.com.
He loves to work with web applications, Mobile apps and Mobile websites using Microsoft technology including
C#, ASP.NET, ASP.NET MVC, SQL Server, WCF, WEB API, LINQ, Entity Framework, jQuery, jQuery UI, jQuery
Mobile, Knockout.js, Windows Azure, Backbone.js, PhoneGap and many more web technologies.
He strives to be the best he can be. He always tries to gain more knowledge and skills in Microsoft technologies.
He always keeps up with new technologies and learning new skills that allow him to provide better solutions to
problems.
• [email protected]
• [email protected]
I am always happy to hear from my readers. Please provide with your valuable feedback and comments!
Table of Contents
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 5
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
Q8. How Model, View and Controller communicate with each other in ASP.NET MVC? ............................. 14
Q11. What is difference between 3-layer architecture and MVC architecture? ............................................. 17
Q12. What is difference between ASP.NET WebForm and ASP.NET MVC? .................................................... 17
Q20. How to define Attribute Routing for Area in ASP.NET MVC? .................................................................. 25
Q30. Can you remove default View Engine in ASP.NET MVC? ........................................................................ 29
Q38. What are various configuration options for AJAX Helpers? .................................................................... 35
Q47. What are different ways of rendering layout in ASP.NET MVC? ............................................................. 39
Q49. What are different ways of returning/rendering a view in ASP.NET MVC? ............................................ 40
Q50. What are differences among ViewData, ViewBag, TempData and Session? .......................................... 41
Q58. How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE? ................. 45
Q59. How to determine an action method is invoked by HTTP GET or POST? ................................................ 46
Q64. How to enable and disable client-side validation in ASP.NET MVC? ...................................................... 48
Q68. Can we use Bundling and Minification in ASP.NET MVC3 or ASP.NET4.0? ............................................. 52
Q72. What are different ways of rendering a Partial View in ASP.NET MVC? ................................................. 52
Q84. How Forms Authentication and Authorization work in ASP.NET MVC? ................................................. 60
Q85. How to implement custom Forms Authentication and Authorization in MVC? ..................................... 62
Q6. What is difference between WCF and WEB API and WCF REST and Web Service? ................................ 79
Q7. Which one to choose between WCF and WEB API?................................................................................ 80
Q8. What is difference between ASP.NET MVC and ASP.NET WEB API?....................................................... 81
Q9. Can you return view by using WEB API method? ....................................................................................
81
Q10. Can you change WEB API action name like ASP.NET MVC? .................................................................... 82
Q11. Can you restrict a WEB API action method to be invoked only by HTTP GET, POST, PUT or DELETE? ... 82
Q12. How to call WEB API in ASP.NET MVC? ................................................................................................... 82
Q13. How ASP.NET WEB API routing is different from ASP.NET MVC routing? .............................................. 83
Q14. How to enable Attribute Routing in ASP.NET WEB API2? ....................................................................... 83
Q15. How to define attribute routing in ASP.NET WEB API2? ......................................................................... 83
1
ASP.NET MVC
Q1. What is MVC?
Ans. MVC stands for Model-View-Controller. It is a software design pattern which was introduced in 1970s. Also,
MVC pattern forces a separation of concerns, it means domain model and controller logic are decoupled from
user interface (view). As a result maintenance and testing of the application become simpler and easier.
Model - The Model represents a set of classes that describe the business logic i.e. business model as well as data
access operations i.e. data model. It also defines business rules for data means how the data can be changed and
manipulated.
View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the
data that is received from the controller as the result. This also transforms the model(s) into UI.
Controller - The Controller is responsible to process incoming requests. It receives input from users via the View,
then process the user's data with the help of Model and passing the results back to the View. Typically, it acts as
the coordinator between the View and the Model.
Today, this pattern is used by many popular framework like as Ruby on Rails, Spring Framework, Apple iOS
Development and ASP.NET MVC.
The main components of DDD are: Entity, Value Object, Aggregate, Service and Repository.
Entity- An object that has an identity- it is unique within the system, like Customer, Employee etc.
Value Object- An object that has no identity within the system like Rate, State etc.
Aggregate: An aggregate root is a special kind of entity that consumers refer to directly. All consumers of the
aggregate root are called as aggregate. The aggregate root guarantees the consistency of changes being made
within the aggregate.
Service- A service is a way of dealing with actions, operations and activities within your application.
Repository- A repository is responsible to store and to retrieve your data. It is not a concern how and where
data will be persist. So, it can be SQL server, oracle, xml, text file or anything else. Repository is not a Data
Access Layer but it refers to a location for storage, often for safety or preservation.
Model - The Model represents a set of classes that describes the business logic and data. It also defines business
rules for data means how the data can be changed and manipulated.
View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the
data that is received from the presenter as the result. This also transforms the model(s) into UI.
Presenter - The Presenter is responsible for handling all UI events on behalf of the view. This receive input from
users via the View, then process the user's data with the help of Model and passing the results back to the View.
Unlike view and controller, view and presenter are completely decoupled from each other’s and communicate to
each other’s by an interface.
Also, presenter does not manage the incoming request traffic as controller.
This pattern is commonly used with ASP.NET Web Forms applications which require to create automated unit
tests for their code-behind pages. This is also used with windows forms.
Model - The Model represents a set of classes that describes the business logic and data. It also defines business
rules for data means how the data can be changed and manipulated.
View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the
data that is received from the controller as the result. This also transforms the model(s) into UI.
View Model - The View Model is responsible for exposing methods, commands, and other properties that helps
to maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events
in the view itself.
This pattern is commonly used by the WPF, Silverlight, Caliburn, nRoute etc.
The Model in ASP.NET MVC can be broken down into several different layers as given below:
1. Objects or ViewModel or Presentation Layer - This layer contains simple objects or complex objects
which are used to specify strongly-typed view. These objects are used to pass data from controller to
stronglytyped view and vice versa. The classes for these objects can have specific validation rules which
are defined by using data annotations. Typically, these classes have those properties which you want to
display on corresponding view/page.
2. Business Layer - This layer helps you to implement your business logic and validations for your
application. This layer make use of Data Access Layer for persisting data into database. Also, this layer is
directly invoked by the Controller to do processing on input data and sent back to view.
3. Data Access Layer - This layer provides objects to access and manipulate the database of your
application. Typically, this layer is made by using ORM tools like Entity Framework or NHibernate etc.
By default, models are stored in the Models folder of an ASP.NET MVC application.
The view is only responsible for displaying the data that is received from the controller as a result. It also
responsible for transforming a model or models into UI which provide all the required business logic and
validation to the view.
By default, views are stored in the Views folder of an ASP.NET MVC application.
The Controller in ASP.NET MVC, respond to HTTP requests and determine the action to take based upon the
content of the incoming request. It receives input from users via the View, then process the user's data with the
help of Model and passing the results back to the View.
By default, controllers are stored in the Controllers folder an ASP.NET MVC application.
Q8. How Model, View and Controller communicate with each other in ASP.NET MVC?
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 14
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
Ans. There are following rules for communication among Model, View and Controller:
5. Model and View cannot talk to each other directly. They communicate to each other with the help of
controller.
• Separation of concern - MVC design pattern divides the ASP.NET MVC application into three main
aspects Model, View and Controller which make it easier to manage the application complexity.
• TDD - The MVC framework brings better support to test-driven development.
• Extensible and pluggable - MVC framework components were designed to be pluggable and extensible
and therefore can be replaced or customized easier then Web Forms.
• Full control over application behaviour - MVC framework doesn’t use View State or server based forms
like Web Forms. This gives the application developer more control over the behaviors of the application
and also reduces the bandwidth of requests to the server.
• ASP.NET features are supported - MVC framework is built on top of ASP.NET and therefore can use
most of the features that ASP.NET include such as the providers architecture, authentication and
authorization scenarios, membership and roles, caching, session and more.
• URL routing mechanism - MVC framework supports a powerful URL routing mechanism that helps to
build a more comprehensible and searchable URLs in your application. This mechanism helps to the
application to be more addressable from the eyes of search engines and clients and can help in search
engine optimization.
ASP.NET MVC1
ASP.NET MVC2
ASP.NET MVC3
ASP.NET MVC4
ASP.NET MVC5
MVC architecture separates the application into three components which consists of Model, View and
Controller. In MVC architecture, user interacts with the controller with the help of view. MVC is a triangle
architecture.
MVC does not replace 3-layer architecture. Typically 3-layer and MVC are used together and MVC acts as the
Presentation layer.
• ViewModel contain fields that are represented in the view (for LabelFor, EditorFor, DisplayFor helpers)
ViewModel can have specific validation rules using data annotations.
• ViewModel can have multiple entities or objects from different data models or data source.
1. 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.
2. 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.
4.1 View Initialization and Rendering - View Initialization and Rendering execution occurs in the following steps:
• ViewResult type i.e. view and partial view are represented by IView (System.Web.Mvc.IView) interface
and rendered by the appropriate View Engine.
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 21
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request
to the appropriate controller and action. If there is no match in the route table for the incoming request's URL, it
returns a 404 HTTP status code.
Always remember route name should be unique across the entire application. Route name can’t be duplicate.
In above example we have defined the Route Pattern {controller}/{action}/{id} and also provide the default
values for controller, action and id parameters. Default values means if you will not provide the values for
controller or action or id defined in the pattern then these values will be serve by the routing system.
Suppose your webapplication is running on www.example.com then the url pattren for you application will be
www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action
name and id if it is required. If you will not provide any of the value then default values of these parameters will
be provided by the routing system. Here is a list of URLs that match and don't match this route pattern.
Request URL Parameters
http://example.com/ controller=Home, action=Index, id=none, Since
default value of controller and action are Home and
Index respectively.
http://example.com/Admin controller=Admin, action=Index, id=none, Since
default value of action is Index
http://example.com/Admin/Product controller=Admin, action=Product, id=none
http://example.com/Admin/Product/1 controller=Admin, action=Product, id=1
http://example.com/Admin/Product/SubAdmin/1 No Match Found
http://example.com/Admin/Product/SubAdmin/Add/1 No Match Found
Note: Always put more specific route on the top order while defining the routes, since routing system check the
incoming URL pattern form the top and as it get the matched route it will consider that. It will not checked
further routes after matching pattern.
Ans. ASP.NET MVC5 and WEB API 2 supports a new type of routing, called attribute routing. In this routing,
attributes are used to define routes. Attribute routing provides you more control over the URIs by defining
routes directly on actions and controllers in your ASP.NET MVC application and WEB API.
1. Controller level routing – You can define routes at controller level which apply to all actions within the
controller unless a specific route is added to an action.
[RoutePrefix("MyHome")]
[Route("{action=index}")] //default action public
class HomeController : Controller
{
//new route: /MyHome/Index
public ActionResult Index()
{
return View();
}
2. Action level routing – You can define routes at action level which apply to a specific action with in the
controller.
public class HomeController : Controller
{
[Route("users/{id:int:min(100)}")] //route: /users/100
public ActionResult Index(int id)
{
//TO DO:
return View();
}
return View();
}
//route: /Home/Contact
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
Note:
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. You simply add an attribute to the
controller action as:
[Route("clients/{clientId}/orders")]
public IEnumerable<Order> GetOrdersByClient(int clientId) {
//TO DO
}
//convention-based routing
routes.MapRoute( name:
"Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional });
}
}
Q20. How to define Attribute Routing for Area in ASP.NET MVC?
Ans. You can also define attribute routing for a controller that belongs to an area by using the RouteArea
attribute. When you define attribute routing for all controllers with in an area, you can safely remove the
AreaRegistration class for that area.
[RouteArea("Admin")]
[RoutePrefix("menu")] [Route("{action}")]
public class MenuController : Controller
{
// route: /admin/menu/login
public ActionResult Login()
{
return View();
}
// route: /admin/menu/products
[Route("products")]
public ActionResult GetProducts()
{
return View();
}
// route: /categories
[Route("~/categories")] public ActionResult Categories()
{
return View();
}
}
• URL rewriting is focused on mapping one URL (new url) to another URL (old url) while routing is focused
on mapping a URL to a resource.
• URL rewriting rewrites your old url to new one while routing never rewrite your old url to new one but it
map to the original route.
Suppose we have defined the following route in our application and you want to restrict the incoming request
url with numeric id only.Now let's see how to do it with the help of regular expression.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route
Pattern new { controller =
"Home", action = "Index",
id = UrlParameter.Optional
} // Default values for parameters );
}
Now for this route, routing engine will consider only those URLs which have only numeric id like as
http://example.com/Admin/Product/1 else it will considers that url is not matched with this route.
• System.Web.Mvc - This namespace contains classes and interfaces that support the MVC pattern for
ASP.NET Web applications. This namespace includes classes that represent controllers, controller
factories, action results, views, partial views, and model binders.
• System.Web.Mvc.Ajax - This namespace contains classes that supports Ajax scripting in an ASP.NET
MVC application. The namespace includes support for Ajax scripts and Ajax option settings as well.
• System.Web.Mvc.Html – This namespace contains classes that help render HTML controls in an MVC
application. This namespace includes classes that support forms, input controls, links, partial views, and
validation.
1. ViewEngine class - This class implements the IViewEngine interface and responsible for locating view
templates.
2. View class - This class implements the IView interface and responsible for combining the template with
data from the current context and convert it to output HTML markup.
3. Template parsing engine - This parses the template and compiles the view into executable code.
@ Html.ActionLink("SignUp", "SignUp")
Q28. How to make Custom View Engine?
Ans. ASP.NET MVC is an open source and highly extensible framework. You can create your own View engine by
Implementing IViewEngine interface or by inheriting VirtualPathProviderViewEngine abstract class.
public class CustomViewEngine : VirtualPathProviderViewEngine
{
public CustomViewEngine()
{
// Define the location of the View and Partial View
this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.html",
"~/Views/Shared/{0}.html" };
this.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.html",
"~/Views/Shared/{0}.html" };
}
protected override IView CreatePartialView(ControllerContext
controllerContext, string partialPath)
{
var physicalpath =
controllerContext.HttpContext.Server.MapPath(partialPath);
return new CustomView(physicalpath);
}
protected override IView CreateView(ControllerContext controllerContext,
string viewPath, string masterPath)
{
var physicalpath =
controllerContext.HttpContext.Server.MapPath(viewPath);
return new CustomView(physicalpath);
}
}
public class CustomView : IView
{
private string _viewPhysicalPath;
writer.Write(parsedcontents);
}
public string Parse(string contents, ViewDataDictionary viewdata)
{
return Regex.Replace(contents, "\\{(.+)\\}", m => GetMatch(m,
viewdata)); }
public virtual string GetMatch(Match m, ViewDataDictionary viewdata)
{
if (m.Success)
{
string key = m.Result("$1");
if (viewdata.ContainsKey(key))
{
return viewdata[key].ToString();
}
}
return string.Empty;
}
}
ViewEngines.Engines.Clear(); }
Q31. What is difference between Razor and WebForm engine?
Ans. The main differences between ASP.NET Web Form and ASP.NET MVC are given below:
Razor Engine is an advanced view engine that was Web Form Engine is the default view engine for the
introduced with MVC3. This is not a new language Asp.net MVC that is included with Asp.net MVC from the
but it is a new markup syntax. beginning.
Razor Engine is an advanced view engine that was Web Form Engine is the default view engine for the
introduced with MVC3. This is not a new language Asp.net MVC that is included with Asp.net MVC from the
but it is a new markup syntax. beginning.
The namespace for Razor Engine is The namespace for Webform Engine is
System.Web.Razor. System.Web.Mvc.WebFormViewEngine.
The file extensions used with Razor Engine are The file extensions used with Web Form Engine are also
different from Web Form Engine. It has .cshtml like Asp.net Web Forms. It has .aspx extension for
(Razor with C#) or .vbhtml (Razor with VB) views, .ascx extension for partial views & editor
extension for views, partial views, editor templates templates and .master extension for layout/master
and for layout pages. pages.
Razor has new and advance syntax that are Web Form Engine has the same syntax like Asp.net Web
compact, expressive and reduces typing. Forms uses for .aspx pages.
Razor syntax are easy to learn and much clean Web Form syntax are borrowed from Asp.net Web Forms
than Web Form syntax. Razor uses @ symbol to syntax that are mixed with html and sometimes make a
make the code like as: view messy. Webform uses <% and %> delimiters to
@Html.ActionLink("SignUp", "SignUp") make the code like as:
<%: Html.ActionLink("SignUp", "SignUp") %>
By default, Razor Engine prevents XSS attacks Web Form Engine does not prevent XSS attacks means
(Cross-Site Scripting Attacks) means it encodes the any script saved in the database will be fired while
script or html tags like <, > before rendering to rendering the page
view.
Razor Engine is little bit slow as compared to Web Form Engine is faster than Razor Engine.
Webform Engine.
Razor Engine, doesn't support design mode in Web Form engine support design mode in visual studio
visual studio means you cannot see your page look means you can see your page look and feel without
and feel. running the application.
Razor Engine support TDD (Test Driven Web Form Engine doesn't support TDD (Test Driven
Development) since it is not depend on Development) since it depend on System.Web.UI.Page
System.Web.UI.Page class. class which makes the testing complex.
Q32. What are HTML Helpers in ASP.NET MVC?
Ans. An HTML Helper is just a method that returns a HTML string. The string can represent any type of content
that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>,
<button> and <img> tags etc.
You can also create your own HTML Helpers to render more complex content such as a menu strip or an HTML
table for displaying database data.
1. Inline Html Helpers - These are create in the same view by using the Razor @helper tag. These helpers
can be reused only on the same view.
ListingItems(string[] items)
@helper
{
<ol> foreach (string item in items)
@
{ <li>@item</li>
} >
</ol
}
Programming Languages:</h3>
@ Book List:</h3>
2. Built-In Html Helpers - Built-In Html Helpers are extension methods on the HtmlHelper class. The Built-
In Html helpers can be divided into three categories-
• Standard Html Helpers - These helpers are used to render the most common types of HTML elements
like as HTML text boxes, checkboxes etc. A list of most common standard html helpers is given below:
HTML Element Example
TextBox @Html.TextBox("Textbox1", "val") Output:
<input id="Textbox1" name="Textbox1" type="text" value="val" />
• Strongly Typed HTML Helpers - These helpers are used to render the most common types of HTML
elements in strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements are
created based on model properties.
The strongly typed HTML helpers work on lambda expression. The model object is passed as a value to
lambda expression, and you can select the field or property from model object to be used to set the id,
name and value attributes of the HTML helper. A list of most common strongly-typed html helpers is
given below:
• Templated HTML Helpers - These helpers figure out what HTML elements are required to render based
on properties of your model class. This is a very flexible approach for displaying data to the user,
although it requires some initial care and attention to set up. To setup proper HTML element with
Templated HTML Helper, make use of DataType attribute of DataAnnitation class.
For example, when you use DataType as Password, A templated helper automatically render Password
type HTML input element.
3. Custom Html Helpers - You can also create your own custom helper methods by creating an extension
method on the HtmlHelper class or by creating static methods with in a utility class.
if (isReadonly)
{
html =
System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
expression, new { @class = "readOnly",
@readonly = "read-only" });
}
else {
html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
expression);
}
return html;
}
}
Q34. What are Url Helpers?
Ans. Url helpers allows you to render HTML links and raw URLs. The output of these helpers is dependent on the
routing configuration of your ASP.NET MVC application.
HTML Element Example
Relative URL @Url.Content("~/Files/asp.netmvc.pdf")
Output: /Files/asp.netmvc.pdf
Based on @Html.ActionLink("About Us", "About", "Home")
action/controller Output: <a href="/Home/About">About Us</a>
@Html.ActionLink("About Me", "About", "Home", "http","www.dotnet-tricks.com",
null,null,null) Output:
<a href="https://www.dotnet-tricks.com/Home/About ">About Me</a>
Ans. The ValidationSummary helper displays an unordered list of all validation errors in the ModelState
dictionary. It accepts a boolean value (i.e. true or false) and based on boolean value it display the errors. When
boolean parameter value is true, it shows only model-level errors and excludes model property-level errors (i.e
any errors that are associated with a specific model property). When Boolean value is false, it shows both
model-level and property-level errors.
Suppose, you have the following lines of code somewhere in the controller action rendering a view:
In the first error there is no key to associate this error with a specific property. In the second error there is a key
named as “Title” to associate this error for model property Title.
@ Html.ValidationSummary(true) *//shows model-level @
@ errors*
@ Html.ValidationSummary(false) @*//shows model-level and property-level @
errors*
Hence, when boolean type parameter value is true then ValidationSummary will display only model-level errors
and exclude property-level errors. It will display Model-level and property-level errors, when boolean type
parameter value is false.
Confirm Specify a message that will be displayed in a confirm dialog to the end user. When
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 36
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
user clicks on OK button in the confirmation dialog, the Ajax call performs.
Specify a JavaScript function name which is called at the beginning of the Ajax
OnBegin request.
OnComplete Specify a JavaScript function name which is called at the end of the Ajax request.
Specify a JavaScript function name which is called when the Ajax request is
OnSuccess successful.
OnFailure Specify a JavaScript function name which is called if the Ajax request fails.
Specify progress message container’s Id to display a progress message or
LoadingElementId animation to the end user while an Ajax request is being made.
Specify a time duration in milliseconds that controls the duration of the progress
LoadingElementDuration message or animation.
Specify the target container’s Id that will be populated with the HTML returned by
UpdateTargetId the action method.
Specify the way of populating the target container. The possible values are
InsertionMode InsertAfter, InsertBefore and Replace (which is the default).
Q39. What is Cross Domain AJAX?
Ans. By default, web browsers allows AJAX calls only to your web application’s site of origin i.e. site hosted
server. This restriction help us to prevent various security issues like cross site scripting (XSS) attacks. But,
sometimes you need to interact with externally hosted API(s) like Twitter or Google. Hence to interact with
these external API(s) or services your web application must support JSONP requests or Cross-Origin Resource
Sharing (CORS). By default, ASP.NET MVC does not support JSONP or Cross-Origin Resource Sharing. For this you
need to do a little bit of coding and configuration.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 37
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
</html>
You can use a layout to define a common template for your site. A layout can be declared at the top of view as:
@{ Layout = "~/Views/Shared/SiteLayout.cshtml";
}
Q41. What are Sections in ASP.NET MVC?
Ans. A section allow you to specify a region of content within a layout. It expects one parameter which is the
name of the section. If you don’t provide that, an exception will be thrown. A section in a layout page can be
defined by using the following code.
@section </h1>
header{
<h1>Header Content
}
You can render above defined section header on the content page as given below:
@ RenderSection("header")
By default, sections are mandatory. To make sections optional, just provides the second parameter value as
false, which is a Boolean value.
@ RenderSection("header",false)
Note: A view can define only those sections that are referred to in the layout page otherwise an exception will be thrown.
@RenderSection("scripts",false)
@section scripts{
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
}
</body>
RenderPage method also exists in the Layout page to render other page exists in your application. A layout page
can have multiple RenderPage method.
@ RenderPage("~/Views/Shared/_Header.cshtml")
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
Styles.Render and Scripts.Render generate multiple style and script tags for each item in the CSS bundle and
Script bundle when optimizations are disabled. When optimizations are enabled, Styles.Render and
Scripts.Render generate a single style and script tag to a version-stamped URL which represents the entire bundle
for CSS and Scripts.
By default ASP.NET MVC project has a _ViewStart.cshtml file in the Views directory and it specifies a default
layout for your ASP.NET MVC application as shown below:
@{ Layout = "~/Views/Shared/Layout.cshtml";
}
Since this code runs before any view, hence a view can override the Layout property and choose a different
layout.
1. Using _ViewStart file in the root directory of the Views folder: The _ViewStart file with in Views folder is used to
server the default Layout page for your ASP.NET MVC application. You can also change the default rendering of
layouts with in _ViewStart file based on controller as shown below:
@{ var
controlle
r =
HttpContext.Current.Request.RequestContext.RouteData.Values["Controll
er"].ToSt ring();
string layout =
""; if
(controller ==
"Admin")
{
layout = "~/Views/Shared/_AdminLayout.cshtml";
layout = "~/Views/Shared/_Layout.cshtml";
}
} Layout = layout;
You can also set the default layout for a particular directory by putting _ViewStart file in each of the
directories with the required Layout information as shown below:
@{ Layout = "~/Views/Shared/_AdminLayout.cshtml";
• BundleConfig.cs - This is used to create and register bundles for CSS and JS files. By default, various
bundles are added in this files including jQuery, jQueryUI, jQuery validation, Modernizr, and Site CSS.
• FIlterConfig.cs - This is used to register global MVC filters like error filters, actions filters etc. By default it
contains HandleErrorAttribute filter.
• RouteConfig.cs - This is used to register various route patterns for your ASP.NET MVC application. By
default, one route is registered here named as Default Route.
• WebApiConfig.cs - This is used to register various WEB API routes like as ASP.NET MVC, as well as set
any additional WEB API configuration settings.
1. Return View() - This tells MVC to generate HTML to be displayed for the specified view and sends it to the
browser. This acts like as Server.Transfer() in ASP.NET WebForm.
2. Return RedirectToAction() - This tells MVC to redirect to specified action instead of rendering HTML. In this
case, browser receives the redirect notification and make a new request for the specified action. This acts
like as Response.Redirect() in ASP.NET WebForm.
Moreover, RedirectToAction construct a redirect url to a specific action/controller in your application and
use the route table to generate the correct URL. RedirectToAction cause the browser to receive a 302
redirect within your application and gives you an easier way to work with your route table.
3. Return Redirect() - This tells MVC to redirect to specified URL instead of rendering HTML. In this case,
browser receives the redirect notification and make a new request for the specified URL. This also acts like
as Response.Redirect() in ASP.NET WebForm. In this case, you have to specify the full URL to redirect.
Moreover, Redirect also cause the browser to receive a 302 redirect within your application, but you have
to construct the URLs yourself.
4. Return RedirectToRoute() - This tells MVC to look up the specifies route into the Route table that is defined
in global.asax and then redirect to that controller/action defined in that route. This also make a new request
like RedirectToAction().
Note:
1. Return View doesn't make a new requests, it just renders the view without changing URLs in the browser's
address bar.
2. Return RedirectToAction makes a new requests and URL in the browser's address bar is updated with the
generated URL by MVC.
3. Return Redirect also makes a new requests and URL in the browser's address bar is updated, but you have to
specify the full URL to redirect
4. Between RedirectToAction and Redirect, best practice is to use RedirectToAction for anything dealing with
your application actions/controllers. If you use Redirect and provide the URL, you'll need to modify those
URLs manually when you change the route table.
5. RedirectToRoute redirects to a specific route defined in the Route table.
Q50. What are differences among ViewData, ViewBag, TempData and Session?
Ans. In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to
view and in next request. Like WebForm, you can also use Session to persist data during a user session.
ViewData
ViewBag
• ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
• Basically it is a wrapper around the ViewData and also used to pass data from controller to
corresponding view.
• Its life also lies only during the current request.
• If redirection occurs then its value becomes null.
• It doesn’t required typecasting for getting data.
TempData
• TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives
session.
• TempData is used to pass data from current request to subsequent request (means redirecting from one
page to another).
• Its life is very short and lies only till the target view is fully loaded.
• It’s required typecasting for getting data and check for null values to avoid error.
• It’s used to store only one time messages like error messages, validation messages.
Session
• Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it never
expires.
• Session is valid for all requests, not for a single redirect.
• It’s also required typecasting for getting data and check for null values to avoid error.
• void Keep() - Calling this method with in the current action ensures that all the items in TempData are
not removed at the end of the current request.
public ActionResult Index()
{
ViewBag.Message = TempData["Message"];
Employee emp = TempData["emp"] as Employee; //need type casting
TempData.Keep();//persist all strings values
return View();
}
• void Keep(string key) - Calling this method with in the current action ensures that specific item in
TempData is not removed at the end of the current request.
public ActionResult Index()
{
ViewBag.Message = TempData["Message"];
Employee emp = TempData["emp"] as Employee; //need type casting
//persist only data for emp key and Message key will be destroy
TempData.Keep("emp");
return View();
}
Q52. How to control Session behavior in ASP.NET MVC?
Ans. By default, ASP.NET MVC support session state. Session is used to store data values across requests.
Whether you store some data values with in the session or not ASP.NET MVC must manage the session state for
all the controllers in your application that is time consuming. Since, session is stored on server side and
consumes server memory, hence it also affect your application performance.
If some of the controllers of your ASP.NET MVC application are not using session state features, you can disable
session for those controller and can gain slight performance improvement of your application. You can simplify
session state for your application by using available options for session state.
In ASP.NET MVC4, SessionState attribute provides you more control over the behavior of session-state by
specifying the value of SessionStateBehavior enumeration as shown below:
Value Description
Default The default ASP.NET behavior is used to determine the session state behavior.
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 44
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
1. ViewResult - Returns a ViewResult which renders the specified or default view by using controller View()
helper method.
2. PartialViewResult - Returns a PartialViewResult which renders the specified or default partial view
(means a view without its layout) by using controller PartialView() helper method.
3. RedirectResult - Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL
by using controller Redirect() helper method.
[NonAction]
public void DoSomething()
{
// Method logic
Now, DoSomething action will be identified and called by the name DoAction.
Q58. How to restrict an action method to be invoked only by HTTP GET, POST, PUT or
DELETE?
Ans. By default, each and every action method can be invoked by any HTTP request (i.e. GET, PUT, POST, and
DELETE). But you can restrict an action to be invoked only by a specific HTTP request by applying HttpGet or
HttpPost or HttpPut or HttpDelete attribute.
If you want to restrict an action method for HTTP Get request only then decorate it with HttpGet action method
selector attribute as given below:
[HttpGet]
public ActionResult Index()
{
//TODO:
return View();
}
Q59. How to determine an action method is invoked by HTTP GET or POST?
Ans. By using HttpMethod property of HttpRequestBase class, you can find out whether an action is invoked by
HTTP GET or POST.
public ActionResult Index(int? id)
{
if (Request.HttpMethod == "GET")
{
//TODO:
}
else if (Request.HttpMethod == "POST")
{
//TODO:
}
else
{
//TODO:
}
return View();
}
Q60. How to determine an AJAX request?
Ans. You can determine an AJAX request by using Request.IsAjaxRequest() method. It will return true, if the
request is an AJAX request else returns false.
Data Annotations help us to define the rules to the model classes or properties for data validation and displaying
suitable messages to end users.
In ASP.NET MVC, there are two ways to validate a model on server side:
1. Explicit Model Validation – This is the traditional way to validate the model data by using IF..Else..IF
statement. In this way, you need to check your model property values one by one for your desired
result.
If model property values are unexpected, inject error messages within ModelState.
class HomeController : Controller
{
[HttpPost]
public ActionResult ExplicitServer(UserViewModel model)
{
//Write custom logic to validate UserViewModel
if (string.IsNullOrEmpty(model.UserName))
{
ModelState.AddModelError("UserName", "Please enter your
name"); }
if (!string.IsNullOrEmpty(model.UserName))
{
Regex emailRegex = new Regex(".+@.+\\..+");
if (!emailRegex.IsMatch(model.UserName))
ModelState.AddModelError("UserName", "Please enter correct
email address");
}
if (ModelState.IsValid) //Check model state
{
//TO DO:
}
}
}
2. Model Validation with Data Annotations - Data Annotations was introduced with .NET 3.5 SP1. It has a
set of attributes and classes defined in the System.ComponentModel.DataAnnotations assembly. Data
Annotations allow us to decorate model classes with metadata. This metadata describes a set of rules
that are used to validate a property.
public class UserViewModel
{
[Required(ErrorMessage = "Please Enter Email Address")]
[RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter
Correct Email Address")]
public string UserName { get; set; }
3.
A When server side model validation fails, errors are included in the ModelState. Hence, by
ns using
.
ModelState.IsValid property you can verify model state. It returns true if there is no error in ModelState else
returns false.
[HttpPost]
public ActionResult DoSomething(UserViewModel model)
{
if (ModelState.IsValid)
{
//TODO: }
return View();
}
For client-side validation, the values of above both the keys must be true. When we create new project using
Visual Studio in MVC3 or MVC4, by default the values of both the keys are set to true.
We can also enable the client-side validation programmatically. For this we need to do code with in the
Application_Start() event of the Global.asax, as shown below.
We can also enable or disable client-side validation for a specific view. For this we required to enable or disable
client side validation inside a Razor code block as shown below. This option will overrides the application level
settings for that specific view.
@using MvcApp.Models
@
{ ViewBag.Title = "About";
HtmlHelper.ClientValidationEnabled = false;
}
Q65. What is a CDN and advantages of CDN?
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 50
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
Ans. CDN stands for content delivery network or content distribution network (CDN) which is a large distributed
system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve the
content (like jQuery library and other open source libraries) to end-users with high availability and high
performance.
// Google CDN
<scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.9
.1/jquery.min.js"></script>
// Microsoft CDN
<scripttype="text/javascript"src="http://ajax.microsoft.com/ajax/jquery/
jquery1.9.1.min.js"></script>
// JQuery CDN
<scripttype="text/javascript"src="http://code.jquery.com/jquery-
1.9.1.min.js"></script>
Advantages
2. It saves bandwidth since jQuery and other open libraries/framework will load faster from these CDN.
3. The most important benefit is it will be cached means if a user has visited any site which is using jQuery
framework from any of these CDN and your web application is also using the same CDN for serving the
jQuery then for your application, it will not request the jQuery from CDN.
A bundle is a logical group of files that is loaded with a single HTTP request. You can create style and script
bundle for CSS and Java Scripts respectively by calling BundleCollection class Add() method. All bundles are
create with in BundleConfig.cs file.
bundles.Add(new
StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.min.js")); }
}
Minification is technique for removing unnecessary characters (like white space, newline, tab) and comments
from the JavaScript and CSS files to reduce the size which cause improved load times of a webpage. There are so
many tools for minifying the js and css files. JSMin and YUI Compressor are two most popular tools for minifying
js and css files.
Suppose you have below CSS and JS files on the layout page and run the application in chrome browser and test
no of request and loading time using chrome developer tools as shown below.
In this test, there are 7 request, total data size is 3.96KB and loading time is approximate 296ms.
When you will run the above application with Bundling and Minification of css and js files and test no of request
and loading time using chrome developer tools as shown below.
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/jquery")
In this test, there are only 3 request, total data size is 2.67KB and loading time is approximate 80ms. In this way
by using bundling and minification you have reduced the total no of request, size and loading time.
But bundles automatically takes care of this problem by adding a hash code to each bundle as a query parameter
to the URL as shown below. Whenever you change the content of CSS and JS files then a new has code will be
generated and rendered to the page automatically. In this way, the browser will see a different Url and will fetch
the new copy of CSS and JS.
We can use partial view to display blog comments, product category, social bookmarks buttons, a dynamic
ticker, calendar etc.
It is best practice to create partial view in the shared folder and partial view name is preceded by "_", but it is
not mandatory. The "_" before view name specify that it is a reusable component i.e. partial view.
Q72. What are different ways of rendering a Partial View in ASP.NET MVC?
Ans. There are four methods for rendering a partial view in ASP.NET MVC These are RenderPartial,
RenderAction, Partial and Action helper methods.
Html.RenderPartial
• This method result will be directly written to the HTTP response stream means it used the same
TextWriter object as used in the current webpage/template.
• This method returns void.
• Simple to use and no need to create any action.
• RenderPartial method is useful used when the displaying data in the partial view is already in the
corresponding view model. For example: In a blog to show comments of an article, we would like to use
RenderPartial method since an article information with comments are already populated in the view
model.
@ Html.RenderPartial("_Comments");}
{
• This method is faster than Partial method since its result is directly written to the response stream which
makes it fast.
Html.RenderAction
• This method result will be directly written to the HTTP response stream means it used the same
TextWriter object as used in the current webpage/template.
• For this method, we need to create a child action for the rendering the partial view.
• RenderAction method is useful when the displaying data in the partial view is independent from
corresponding view model. For example: In a blog to show category list on each and every page, we
would like to use RenderAction method since the list of category is populated by the different model.
@ Html.RenderAction("Category","Home");}
{
• This method is the best choice when you want to cache a partial view.
• This method is faster than Action method since its result is directly written to the HTTP response stream
which makes it fast.
Html.Partial
Html.Action
• This method is also the best choice when you want to cache a partial view.
Each MVC area has its own folder structure which allow us to keep separate controllers, views, and models. This
also helps the multiple developers to work on the same web application without interfere to one another.
Always remember the order of registering the Areas must be on top, so that all of the settings, filters and routes
registered for the applications will also apply on the Areas.
This action method can has child attribute and has its independent MVC lifecycle from parent view. Also, an
action which has child attribute cannot be called independently. It always will be called within a parent view
otherwise it would give error.
[ChildActionOnly]
A child action is invoked by using @Html.RenderAction or @Html.Action helper methods from inside of a view.
Scaffolding consists of page templates, entity page templates, field page templates, and filter templates. These
templates are called Scaffold templates and allow you to quickly build a functional data-driven Web site.
Steps to create ASP.NET MVC CRUD operations using scaffolding in ASP.NET MVC: Step1:
The following actions are created for insert, update and delete operations based on scaffold template within
User controller.
Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC application.
1. Custom Authentication
2. Custom Authorization (User based or Role based)
3. Error handling or logging
4. User Activity Logging
5. Data Caching
6. Data Compression
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 59
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
1. Authentication Filters - This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is
used to create CustomAuthentication filter. The definition of this interface is given below-
void OnAuthenticationChallenge(AuthenticationChallengeContext
filterContext);
}
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown
below-
public class CustomAuthenticationFilterAttribute : FilterAttribute,
IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
filterContext.HttpContext.Response.Write("Authentication
Filter<br/>");
}
//Runs after the OnAuthentication method
public void OnAuthenticationChallenge(AuthenticationChallengeContext
filterContext)
{
//TODO: Additional tasks on the request
}
}
2. Authorization Filters - The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter
interface. The definition of this interface is given below-
The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute
class.
In this way you can make your CustomAuthorize filter attribute either by implementing IAuthorizationFilter
interface or by inheriting and overriding above methods of AuthorizeAttribute class.
3. Action Filters - Action filters are executed before or after an action is executed. The IActionFilter interface is
used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted
which will be executed before or after an action is executed respectively.
4. Result Filters - Result filters are executed before or after generating the result for an action. The Action
Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult,
JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called
after the Action filters. The IResultFilter interface is used to create a Result Filter which provides two
methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the
result for an action respectively.
5. Exception Filters - Exception filters are executed when exception occurs during the actions execution or
filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides
OnException method which will be executed when exception occurs during the actions execution or filters
execution.
The HandleErrorAttribute class is one example of an exception filter which implements IExceptionFilter.
When HandleError filter receives the exception it returns an Error view located in the Views/Shared folder
of your ASP.NET MVC application.
Ans. Exception filters are executed if there is an unhandled exception thrown during the execution of the
ASP.NET MVC pipeline.
• Authentication filters
• Authorization filters
• Action filters
• Result filters
1. Global level - By registering your filter into Application_Start event of Global.asax.cs file with the help of
FilterConfig class.
2. Controller level - By putting your filter on the top of the controller name as shown below-
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
//TODO:
}
3. Action level - By putting your filter on the top of the action name as shown below-
<system.web>
<authentication mode="Forms"> <forms loginUrl="Login.aspx" protection="All"
timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true"
defaultUrl="default.aspx" cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />
</authentication>
</system.web>
The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or
RedirectFromLoginPage() methods are called. The value of authentication cookie contains a string
representation of the encrypted and signed FormsAuthenticationTicket object.
You can create the FormsAuthenticationTicket object by specifying the cookie name, version of the cookie,
directory path, issue date of the cookie, expiration date of the cookie, whether the cookie should be persisted,
and optionally user-defined data as shown below:
Now, you can encrypt this ticket by using the Encrypt method FormsAuthentication class as given below:
ASP.NET provides IPrincipal and IIdentity interfaces to represents the identity and role for a user. You can create
a custom solution by evaluating the IPrincipal and IIdentity interfaces which are bound to the HttpContext as
well as the current thread.
public class CustomPrincipal : IPrincipal
{
public IIdentity Identity { get; private set; }
public bool IsInRole(string role)
{
if (roles.Any(r => role.Contains(r)))
{
return true;
}
else
{
return false;
}
}
public CustomPrincipal(string Username)
{
this.Identity = new
GenericIdentity(Username); } public int
UserId { get; set; } public string FirstName {
get; set; } public string LastName { get; set; }
public string[] roles { get; set; } }
Now you can put this CustomPrincipal objects into the thread’s CurrentPrincipal property and into the
HttpContext’s User property to accomplish your custom authentication and authorization process.
A user will be authenticated if IsAuthenticated property returns true. For authenticating a user you can use one
of the following two ways:
1. Thread.CurrentPrincipal.Identity.IsAuthenticated
2. HttpContext.Current.User.Identity.IsAuthenticated
ASP.NET MVC provides Authorization filter to authorize a user. This filter can be applied to an action, a
controller, or even globally. This filter is based on AuthorizeAttribute class. You can customize this filter by
overriding OnAuthorization() method as shown below:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected virtual CustomPrincipal CurrentUser
{
get { return HttpContext.Current.User as CustomPrincipal; }
}
if (!String.IsNullOrEmpty(Users))
{
if (!Users.Contains(CurrentUser.UserId.ToString()))
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
// base.OnAuthorization(filterContext); //returns to login url
}
}
}
}
}
Now you can apply this custom authorization filter at controller or action level for authorization as shown below:
[CustomAuthorize(Roles= "Admin")]
public class AdminController : BaseController
{
public ActionResult Index()
{
return View();
}
}
ValidateInput attribute can enable or disable input validation at the controller level or at any action method.
[ValidateInput(false)]
public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}
}
ValidateInput attribute allow the Html input for all the properties and that is unsafe. Since you have enable
Html input for only one-two properties then how to do this. To allow Html input for a single property, you
should use AllowHtml attribute.
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 66
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
[AllowHtml]
[Required]
[Display(Name = "Description")] public string Description { get; set; }
}
The output of the Index() action method will be cached for 20 seconds. If you will not defined the duration, it will
cached it for by default cache duration 60 sec.
By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. You
can control the content's cached location by changing the location parameter of the OutputCache attribute to
any of the following values: Any, Client,Downstream, Server, None, or ServerAndClient.
By default, the location parameter has the value Any which is appropriate for most the scenarios. But sometimes
there are scenarios when you required more control over the cached data.
Q90. What is Donut caching and Donut hole caching in ASP.NET MVC?
Ans. Donut caching cache an entire web page except for one or more parts of the web page. Before Donut
caching, we have Output Caching which cache the entire web page.
Suppose, you have a web application in which some pages like HomePage,Tools etc. are same for all the users
excepts the user's logged in details like username.
If you want to cache all these pages for all the users by using OutputCache with VaryByParam UserID, then the
entire page would be cached every time for each user with a different user name (or whatever your dynamic
part of the page is). This is not a good practice since there will be 1000 cached pages if there are 1000 logged in
user at a time.
To resolve this issue, Donut Caching was introduced which cached only one copy of the entire page for all the
user except for a small part which remain dynamic. This small part act like as a hole in the cached content and
much like a donut.
Donut caching is very useful in the scenarios where most of the elements in your page are rarely changed except
the few sections that dynamically change, or changed based on a request parameter.
Donut Hole Caching is the inverse of Donut caching means while caching the entire page it cached only a small
part of the page (the donut hole).
Suppose, you have a web application in which ProductCategory is shown on each and every pages so it makes
sense to render all of the categories just once and cache the resulting HTML by using Donut Hole Caching.
Donut Hole caching is very useful in the scenarios where most of the elements in your page are dynamic except
the few sections that rarely change, or changed based on a request parameter. ASP.NET MVC has great support
for Donut Hole caching through the use of Child Actions.
High level modules should not depend upon low level modules. Both should depend upon
abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.
The Dependency Inversion principle (DIP) helps us to develop loosely couple code by ensuring that high-level
modules depend on abstractions rather than concrete implementations of lower-level modules. The Inversion of
Control pattern is an implementation of this principle.
The term Inversion of Control (IoC) refers to a programming style where a framework or runtime, controls the
program flow. Inversion of control means we are changing the control from normal way. It works on
Dependency Inversion Principle. The most software developed on the .NET Framework uses IoC.
More over IoC is a generic term and it is not limited to DI. Actually, DI and Service Locator patterns are
specialized versions of the IoC pattern or you can say DI and Service Locator are the ways of implementing IoC.
For example, suppose your Client class needs to use a Service class component, then the best you can do is to
make your Client class aware of an IService interface rather than a Service class. In this way, you can change the
implementation of the Service class at any time (and for how many times you want) without breaking the host
code.
DIP says High level module should not depend on low level module and both should depend on abstraction. IoC
is a way that provide abstraction. A way to change the control. IoC gives some ways to implement DIP. If you
want to make independent higher level module from the lower level module then you have to invert the control
so that low level module do not control interface and creation of object. Finally IoC gives some way to invert the
control.
The Dependency Injection pattern uses a builder object to initialize objects and provide the required
dependencies to the object means it allows you to "inject" a dependency from outside the class.
For example, suppose your Client class needs to use a Service class component, then the best you can do is to
make your Client class aware of an IService interface rather than a Service class. In this way, you can change the
implementation of the Service class at any time (and for how many times you want) without breaking the host
code.
DI Implementation:
Ans. Service Locator is a software design pattern that also allow us to develop loosely coupled code. It
implements the DIP principle and easier to use with an existing codebase as it makes the overall design looser
without forcing changes to the public interface.
The Service Locator pattern introduces a locator object that objects is used to resolve dependencies means it
allows you to "resolve" a dependency within a class. Above example can be re-written as follows by using SL.
return _Service;
}
}
public class Client
{
private IService _service;
public Client()
{
this._service = LocateService.GetService();
}
public void Start()
{
Console.WriteLine("Service Started");
this._service.Serve();
Console.ReadKey();
}
}
• Constructor Injection - This is the most common DI. Dependency Injection is done by supplying the
DEPENDENCY through the class’s constructor when instantiating that class. Injected component can be
used anywhere within the class. Should be used when the injected dependency is required for the class
to function. It addresses the most common scenario where a class requires one or more dependencies.
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve()
{
Console.WriteLine("Service Called");
Console.ReadKey();
}
}
• Property Injection – This is also called Setter injection. This is used when a class has optional
dependencies, or where the implementations may need to be swapped. This is used by different logger
implementations like Log4Net. It may require checking for a provided implementation throughout the
class (need to check for null before using it). It does not require adding or modifying constructors.
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve()
{
Console.WriteLine("Service Called");
//To Do: Some Stuff
}
}
public class Client
{
private IService _service;
Console.ReadKey();
}
}
• Method Injection – This Inject the dependency into a single method, for use by that method only. It
could be useful where the whole class does not need the dependency, just the one method.
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve()
{
Console.WriteLine("Service Called");
//To Do: Some Stuff
}
}
public class Client
{
private IService _service;
Console.ReadKey();
}
}
Q96. What are advantages of Dependency Injection (DI)?
Ans. There are following advantages of DI:
A DI Container is a framework to create dependencies and inject them automatically when required. It
automatically creates objects based on request and inject them when required. DI Container helps us to manage
dependencies with in the application in a simple and easy way.
We can also manage an application dependencies without a DI Container, but it will be like as POOR MAN’S DI
and we have to do more work, to make it configured and manageable.
Castle Windsor
Spring.NET
• INTERCEPTION
• Comprehensive documentation
• Commercial support available
Autofac
Unity
• INTERCEPTION
• Good documentation
• Consistent API
Ninject
Q100. What are commonly used tool for Unit Testing in ASP.NET MVC?
Ans. ASP.NET MVC has been designed for testability without dependencies on the IIS server, on a
database, or on external classes. There are following popular tools for ASP.NET MVC testing:
• NUnit - This is the most popular unit testing frameworks for Microsoft .NET. Its syntax is relatively simple
and easy to use. It comes with a test runner GUI and a command-line utility. NUnit is also available as a
NuGet package for download.
• xUnit.NET - This provides a way to run automated unit tests. It is simple, easily extended, and has a very
clean syntax.
2
ASP.NET WEB API
Q1. What is REST?
Ans. REST stands for Representational State Transfer. This is a protocol for exchanging data over a distributed
environment. REST is an architectural style which treat each service as a resource and access data by HTTP
protocol methods like GET, POST, PUT, and DELETE.
REST-style architectures consist of clients and servers. Clients initiate requests to servers who process these
requests and return responses based on these requests. These requests and responses are built around the
transfer of representations of these resources.
It is a part of the core ASP.NET platform and can be used with MVC and other types of Web applications like
ASP.NET WebForms. It can also be used as a stand-alone Web services application.
1. It supports convention-based CRUD Actions since it works with HTTP verbs GET, POST, PUT and DELETE.
2. Responses have an Accept header and HTTP status code.
3. Responses are formatted by WEB API’s MediaTypeFormatter into JSON, XML or whatever format you want
to add as a MediaTypeFormatter.
4. It may accepts and generates the content which may not be object oriented like images, PDF files etc.
5. It has automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method
that returns IQueryable, clients can use the method for OData query composition.
6. It can be hosted with in the applicaion or on IIS.
7. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC
container or dependency injection that makes it more simple and robust.
So, if you like to expose your service data to the browsers and as well as all these modern devices apps in fast
and simple way, you should have an API which is compatible with browsers and all these devices.
For example twitter, facebook and Google API for the web application and phone apps.
WEB API is the great framework for exposing your data and service to different-different devices. Moreover WEB
API is open source an ideal platform for building REST-ful services over the .NET Framework. Unlike WCF Rest
service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content
formats) and you don't need to define any extra config settings for different devices unlike WCF Rest service.
1. If we need a Web Service and don’t need SOAP, then ASP.NET WEB API is best choice.
2. It is used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.
3. It doesn't have tedious and extensive configuration like WCF REST service.
4. Simple service creation with WEB API. With WCF REST Services, service creation is difficult.
5. It is only based on HTTP and easy to define, expose and consume in a REST-ful way.
6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
7. It is open source.
Q6. What is difference between WCF and WEB API and WCF REST and Web Service?
Ans. .NET framework has a number of technologies that allow you to create HTTP services such as Web Service,
WCF and now WEB API. There are following differences among these four:
Web Service
WCF
WCF Rest
WEB API
1. This is the new framework for building HTTP services with easy and simple way.
2. WEB API is open source an ideal platform for building REST-ful services over the .NET Framework.
3. Unlike WCF Rest service, it use the full features of HTTP (like URIs, request/response headers, caching,
versioning, various content formats)
4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC
container or dependency injection, unit testing that makes it more simple and robust.
5. It can be hosted with in the application or on IIS.
6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
7. Responses are formatted by WEB API’s MediaTypeFormatter into JSON, XML or whatever format you
want to add as a MediaTypeFormatter.
1. Choose WCF when you want to create a service that should support special scenarios such as one way
messaging, message queues, duplex communication etc.
2. Choose WCF when you want to create a service that can use fast transport channels when available, such
as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all
other transport channels are unavailable.
3. Choose WEB API when you want to create resource-oriented services over HTTP that can use the full
features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
4. Choose WEB API when you want to expose your service to a broad range of clients including browsers,
mobiles, iphone and tablets.
Q8. What is difference between ASP.NET MVC and ASP.NET WEB API?
Ans. There are following differences between ASP.NET MVC and WEB API:
1. ASP.NET MVC is used to create web applications that return both views and data but ASP.NET WEB API is
used to create full blown HTTP services with easy and simple way that returns only data not view.
2. WEB API helps to build REST-ful services over the .NET Framework and it also support
contentnegotiation(it's about deciding the best response format data that could be acceptable by the
client. it could be JSON,XML,ATOM or other formatted data), self-hosting which are not in MVC.
3. WEB API also takes care of returning data in particular format like JSON, XML or any other based upon
the Accept header in the request and you don't worry about that. MVC only return data in JSON format
using JsonResult.
4. In WEB API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to
actions name.
5. ASP.NET WEB API is new framework and part of the core ASP.NET framework. The model binding, filters,
routing and others MVC features exist in WEB API are different from MVC and exists in the new
System.Web.Http assembly. In MVC, these features exist within System.Web.Mvc. Hence WEB API can
also be used with ASP.NET and as a stand-alone service layer.
6. You can mix WEB API and MVC controller in a single project to handle advanced AJAX requests which may
return data in JSON, XML or any others format and building a full blown HTTP service. Typically, this will
be called WEB API self-hosting.
7. When you have mixed MVC and WEB API controller and you want to implement the authorization then
you have to create two filters one for MVC and another for WEB API since both are different.
8. Moreover, WEB API is light weight architecture and except the web application it can also be used with
smart phone apps.
Q10. Can you change WEB API action name like ASP.NET MVC?
Ans. Like ASP.NET MVC, you can also change WEB API action name by using ActionName attribute as
given below:
[HttpGet]
[ActionName("GetProducts")]
public IEnumerable<Product> ProductList()
{
return db.Products.AsEnumerable();
}
Q11. Can you restrict a WEB API action method to be invoked only by HTTP GET, POST, PUT
or DELETE?
Ans. Like ASP.NET MVC, you can also restrict WEB API action method to be invoked only by a specific HTTP
request by applying HttpGet or HttpPost or HttpPut or HttpDelete attribute.
If you want to restrict an action method for HTTP Get request only then decorate it with HttpGet action method
selector attribute as given below:
[HttpGet]
public IEnumerable<Product> ProductList()
{
return db.Products.AsEnumerable();
}
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;
return View(data);
}
return View();
}
}
Q13. How ASP.NET WEB API routing is different from ASP.NET MVC routing?
Ans. ASP.NET MVC and ASP.NET WEB API both use routing to monitor incoming request and at least one route is
defined in order to function. The difference between these two routing is given below:
1. In WEB API route pattern {action} parameter is optional but you can include an {action} parameter. In
ASP.NET MVC {action} parameter is mandatory.
2. The action methods defined in the API controller must either have the HTTP action verbs (GET, POST, PUT,
DELETE) attribute or have one of the HTTP action verbs as a prefix for the actions methods name. In ASP.NET
MVC, by default an action method can be called by HTTP GET or POST verbs and for using others HTTP verbs
you need to defined as an attribute.
3. Unlike ASP.NET MVC, Web API can receive only one complex type as a parameter.
// Convention-based routing.
config.Routes.MapHttpRoute( n
ame: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Q15. How to define attribute routing in ASP.NET WEB API2?
Ans. Like ASP.NET MVC5, you can also define attribute routing in WEB API2 at controller level and action
level as shown below:
1. Controller level routing – You can define routes at controller level which apply to all actions within the
controller unless a specific route is added to an action.
[RoutePrefix("Service/User")]
public class UserController : ApiController
{
//GET route: api/User
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
2. Action level routing – You can define routes at action level which apply to a specific action with in the
controller.
}
}