upGrad KnowledgeHut SkillFest Sale!

ASP.NET Interview Questions and Answers

ASP.NET is a web application framework developed to build dynamic web applications, web services, and web APIs. It is part of the .NET framework and allows developers to create powerful, data-driven websites using various programming languages, including C#, VB.NET, and F#. Our expansive set of ASP.NET interview questions is made for both beginners and advanced-level interviewees. The questions are divided widely, covering topics like Routing and URL management, MVC, MVVM, Web Forms, MVC, and Web API programming models, Cookies, Sessions, Cache, and Testing. Our set of ASP.NET interview questions and answers will make you confident to sit and ace the interview.

  • 4.8 Rating
  • 28 Question(s)
  • 25 Mins of Read
  • 6857 Reader(s)

Beginner

1. Client side:

  1. Hidden Field
  2. ViewState
  3. Cookies
  4. Control State
  5. Query Strings

2. Server side:

  1. Session
  2. Application
  3. Cache

ViewState is a client-side state management mechanism in ASP.NET. It is a default technique used by ASP.NET to persist the value of the page and controls during postbacks.

In ASP.NET ViewState the values are encrypted and stored in a hidden field ( named _VIEWSTATE) on the page as an encoded Base64 string. By default, ViewState is sent to the client browser and then returned to the server in the form of a hidden input control on your page.

Advantages:

  • It works at client side so it doesn't put any load on the server 
  • Easy to implement
  • ViewState ensures security because it stores the data in encrypted format.

Disadvantages:

  • It can be performance overhead if we are going to store a larger amount of data because it is associated with page only.
  • Does not track across pages. ViewState information does not automatically transfer from page to page.
  • A good hacker can get the data very easily by decoding the value of the ViewState. One can’t store sensitive data in the ViewState.
  • It does not have any support for mobile devices.

It's no surprise that this one pops up often in ASP.NET interview questions and answers for freshers.

If the application is storing a lot of data in ViewState, it can affect the overall responsiveness of the page, thereby affecting performance since data is stored on the page itself in hidden controls.

The ideal size of ViewState should be less than 30% of the page size.

DeflateStream and GZipStream are the classes in ASP.NET that provide methods and properties to compress and decompress streams. Using these classes to compress ViewState will reduce its size to around 40%.

  • Page Output Caching:

It keeps a copy of the response that was sent to the client in memory and subsequent requests are then responded with the cached output until the cache expires, which incredibly improves the ASP.NET web application performance. It is implemented by placing an OutputCache directive at the top of the .aspx page at design time.

Example: 

<%@OutputCache Duration="10" VaryByParam= "Id"%>
  • Page Fragment Caching:

Sometimes we might want to cache just portions of a page. For example, we might have a header for our page which will have the same content for all users.  To specify that a user control should be cached, we use the @OutputCache directive just like we used it for the page.

<%@OutputCache Duration=10 VaryByParam="None" %>
  • Data Caching:

Data Cache is used to store frequently used data in the Cache memory. It's much efficient to retrieve data from the data cache instead of database or other sources. We need use System.Web.Caching namespace. The scope of the data caching is within the application domain unlike "session". Every user can able to access these objects.

  • Create: Cache["Employee"] ="DatasetName";
  • Retrieve: Dataset dsEmployee = (Dataset) Cache ["Employee"]

This is a frequently asked question in ASP.NET interview questions.

Output cache functionality is achieved using the OutputCache attribute in the ASP.NET page header. Below is the syntax:

<%@ OutputCache Duration="20" Location="Server" Vary By Param="state" Vary By Custom="minor version" Vary By Header="Accept-Language"%>
  • Vary By Param - Caches different versions depending on input parameters sent through HTTP POST/GET.
  • Vary By Header - Caches different versions depending on the contents of the page header.
  • Vary By Custom - Lets you customize the way the cache handles page variations by declaring the attribute and overriding the Get Vary By Custom string handler.
  • Vary By Control - Caches different versions of a user control based on the value of properties of ASP objects in the control.
  1. Required field Validator
  2. Range Validator
  3. Compare Validator
  4. Custom Validator
  5. Regular expression Validator
  6. Summary Validator

Cookie is a small piece of information stored on the client machine. This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie" path.  It is used to store user preference information like Username, Password, City and PhoneNo etc. on client machines. We need to import namespace called System.Web.HttpCookie before we use a cookie. 

  • Persistent Cookies: Persistent Cookies are Permanent Cookies stored as a text file in the hard disk of the computer. They stay on your hard disk and can be accessed by web servers until they are deleted or have expired. 
  • Non-Persistent Cookies: Non-Persistent cookies are temporary. The cookie which will be alive till that time until your browser is alive, as you will log out to your browser or close your browser, cookies will get expire and user information would also be lost. So they are browser dependent cookies. They are also called in-memory cookies and session-based cookies.

A common question in ASP.NET technical interview questions, don't miss this one.

50 Cookies per domain, with a maximum of 4 KB per cookie (or even 4 KB in total). If you want to support most browsers, then do not exceed 50 cookies per domain and 4093 bytes per domain. That is, the size of all cookies should not exceed 4093 bytes.

Advantages:

  • Cookies are simple to use and implement.
  • Occupies less memory, do not require any server resources and are stored on the user's computer so no extra burden on the server.
  • We can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client’s computer (persistent cookies).
  • Cookies persist a much longer period of time than Session state.

Disadvantages:

  • Cookies are maintained at the client system, so they are not secure
  • A limited number of cookies are allowed for the website (Max 50)
  • A limited amount of data can be maintained (Max 4kb)
  • Only plain text can be maintained

 By using HttpCookie class object. After creating cookie it will be attached to Response Object to send it to the client.

 Ex: 

 HttpCookie cookie1=new HttpCookie ("Username","Ritu"); Response.Cookies.Add (cookie1);

Advantages:

  • Easy to implement.
  • No server resources are required. The query string containing in the HTTP requests for a specific URL
  • Supported by all browsers.

Disadvantages:

  • Many browsers impose a 255 URL character limit which can limit their flexibility.
  • Query string data is visible to the user in URL so they are insecure. 

ASP NET Core developers are sought after by companies for their niche skill sets. These interview questions on ASP.NET will give you a fair idea of the questions which the interviewer asks during an ASP.NET interview. So, prepare well and good luck!

We can cache multiple response from a single web form by using any one of the attributes from VaryByParam, VaryByHeaders or VaryByCustom attributes.

Example: If we want display different country data on our page where we can choose country name from the drop down list. On SelectedIndexChanged event of the Drop down we have to write some logic to fetch the country data according to the selected value and display the data of the particular country. By setting the VaryByParam attribute to the dropdown will cache all the responses received from server on SelectedIndexChanged event of drop down. 

 <%@ OutputCache Duration="20" Location="Server" VaryByParam="countryDropDown%>
<aspx:DropDownList ID="countryDropDown" AutoPostBack="true" runat="server" 
        onselectedindexchanged=" countryDropDown _SelectedIndexChanged">
      <asp:ListItem Text="Germany" Value=" Germany "></asp:ListItem>
      <asp:ListItem Text="Singapore" Value=" Singapore "></asp:ListItem>
       <asp: ListItem Text="India" Value=" India "></asp: ListItem>
    </asp:DropDownList>

Intermediate

A staple in ASP.NET interview questions for advance professionals, be prepared to answer this one.

While programming in C#, we can split the definition of a class over two or more source files. The source files contain a section of the definition of class, and all parts are combined when the application is compiled. For splitting a class definition, we need to use the partial keyword.

Example:

We have a file with a partial class named as Record

namespace HeightWeightInfo
{
   class File1
   {
   }
   public partial class Record
   {
       private int h;
       private int w;
       public Record(int h, int w)
       {
           this.h = h;
           this.w = w;
       }
   }
}

Here is another file named as File2.cs with the same partial class Record

namespace HeightWeightInfo
{
   class File2
   {
   }
   public partial class Record
   {
       public void PrintRecord()
       {
           Console.WriteLine("Height:"+ h);
           Console.WriteLine("Weight:"+ w);
       }
   }
}

The main method of the project

namespace HeightWeightInfo
{
   class Program
   {
       static void Main(string[] args)
       {
           Record myRecord = new Record(10, 15);
           myRecord.PrintRecord();
           Console.ReadLine();
       }
   }
}

State management basically stores the information of user/Page or object when a user makes a request on a web page, since HTTP is a protocol which doesn’t store the information during each request made by the user.so Asp.net state management is used to preserve the data.

  • Client side
  • Hidden Field
  • View State
  • Cookies
  • Control State
  • Query Strings
  • Server side
  • Session
  • Application

Server Side:-

1) Session: when we want to store the data of web page over multiple requests we use session. In this technique we can store any kind of information or object in server memory it basically stores the information. The session is user specific since it stores the information of user separately. When we store data to Session state, a session cookie named is ASP.NET_SessionId is created automatically.

Example:

Storing the data in Session object

Session ["UserName"] = txtName.Text;

Retrieving the data from the Session object

Label1.Text = Session ["UserName"].ToString();

Session timeout is 20 min if we want to increase the timeout of session then we need to configure the web config

<configuration>
 <system.web>
   <sessionState timeout="60" />
 </system.web>
</configuration>

2). Application object: In application object, we can store the information at the application level rather than User level, where every user can access that information .the main disadvantage is that sometimes there is a concurrency problem, so for that, we use a lock and unlock method. So if multiple requests came for same data then only one thread can do work.

Example:

Application["Message"] = "Hello to all";

We can use an application object to count the number of visitors on that website.

Client Side: 

1) Query Strings: When we want to transfer the data over the pages from the URL then we use query string, it cannot handle the huge data and it is compatible with all browsers, we cannot transfer the objects and controls in query strings, so it is not meant for transferring sensitive data through query string.

Example: 

Response.Redirect( "SecondPage.aspx?Type=01&Query=Query1" );

Or if we want to use query string to transfer the data then we can encrypt the sensitive data and we can transfer the data.

2). Control State: It is used to transfer the data which is stored in controls .it is just like same as view state but here we can store the data of the controls like dropdown list`s selected items, we cannot disabled the control state if viewstate is disabled then control state works same as view state.

3). View State: It is one of the finest methods to preserve the data, in view state we can store any kind of data like controls data, and even variables and raw data, view state encrypt the data when it will render to the user, so if user wants to see the value of view state in view source it will contain the symbols only which are very hard to decrypt.

The only disadvantage is that page contains much space over the page. To handle the view state we just need to "EnableViewState = true" attribute to any control to save its state,

Example:

public class Person
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
public partial class default : Web.UI.Pages
{
Person p = new Person();
p.FirstName = "Harshit";
p.LastName = "Mittal";
ViewState["PersonDetails"]=p;
}

4). Cookies: Cookies are used to identify the user on a web page whenever the user makes the request for the first time it stores that request data in the cookies and when the user visit that web page for the second time then browser check the cookies data with second request data made by the user if the result matches browser to consider them as a previous user else consider a new user.

Example: The Case of Remember me on every login page.

There are 2 types of cookies:

  1. Persistence cookies
  2. Non- Persistence cookies
  • Persistence cookies - When we want to store the data in cookies for a specific period of time or for permanent use then we use persistence cookies

Example: 

Response.Cookies["nameWithPCookies"].Value = "This is A Persistence Cookie";
Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10);
  • Non Persistence cookies - In this the data stored in the cookies remain in the client hard disk folder till the time the browser is running when the browser is closed then the information of cookies is lost.

Example: 

Response.Cookies["nameWithNPCookies"].Value = "This is A Non Persistence Cookie";

5) Hidden Field - When we want to store the small amount of data or we can say the if want to save the single value, hidden field controls is not rendered on the client browser, it is invisible to the browser.

Example:  

<asp:HiddenField ID="HiddenField1" runat="server"  />

At the server code

protected void Page_Load(object sender, EventArgs e)
{
  if (HiddenField1.Value != null)
  {
   int val= Convert.ToInt32(HiddenField1.Value) + 1;
   HiddenField1.Value = val.ToString();
   Label1.Text = val.ToString();
  }
}

Advanced

Hashtable
Dictionary
Hashtable included in System.Collections namespace
Dictionary included in System.Collections.Generic namespace
It is weakly structured data type in key values pair we can take any object type
In this strong in a data type that you must have to specify the data type of the key value  pair
Returns null as a result if key which does not exist
Throws exception if we try to find with a key that not exists
It is generic type
It is non-generic type
It is faster since we don’t need to do boxing and unboxing in this
It is slower than hashtable and it involves an additional step of boxing and unboxing
Response.Redirect
Server.Transfer
when we want to transfer the information from one page to another page of the same server
when we want to transfer the data to an HTML page of own server or to some other server
it doesn’t require the query string to preserve the data
It never persists Query Strings and Forms Variables from original request
It causes additional round trips to the server on each request
It preserves server resources and avoids the unnecessary round trips to the server
In this, we need to show the URL  to the user where we are redirecting
the current URL where the page is redirected is not shown in the browser

This question is a regular feature in ASP.NET interview questions for senior developer, be ready to tackle it.

As we know we cannot assign the null value to any value type so for that we use nullable type where we can assign null value to the value type variables.

Syntax:  

Nullable<T> where T is a type.
Nullable type is an instance of System.Nullable<T> struct

Nullable Struct :

[Serializable]

public struct Nullable<T> where T : struct
{        
   public bool HasValue { get; } // it will return true if we assigned a value, if there is no value or if we assign a null value it will return false;
   public T Value { get; }
}
HasValue :
static void Main(string[] args)
{
   Nullable<int> i = null;
   if (i.HasValue)
       Console.WriteLine(i.Value);
   else
       Console.WriteLine("Null");
}

Example: 

[Serializable]

public struct Nullable<T> where T : struct
{        
   public bool HasValue { get; }
   public T Value { get; }
}
static void Main(string[] args)
{
   Nullable<int> i = null;
   if (i.HasValue)
       Console.WriteLine(i.Value); // or Console.WriteLine(i)
   else
       Console.WriteLine("Null");
}

Output:

Null

It will check whether an object has been assigned a value if it is having null value it will return false and the else part will be executed.

To get the value of i using the nullable type you have to use GetValueOrDefault() method to get the actual value.

static void Main(string[] args)
{
   Nullable<int> i = null;
   Console.WriteLine(i.GetValueOrDefault());
}

Extension methods allow you to add our own custom method in any custom class without modifying into it and in our custom class and it will be available throughout the application by specifying namespace only where it is defined.

Example: 

namespace ExtensionMethod
{
   public static class IntExtension
    {
       public static bool IsGreaterThan(this int i, int value)
       {
           return i > value;
       }
   }
}

Here the first parameter specifies the type on which the extension method is applicable. We are going to use this extension method on int type. So the first parameter must be int preceded with the modifier.

using ExtensionMethod;
class Program
{
   static void Main(string[] args)
   {
       int i = 10;
       bool result = i.IsGreaterThan(100);
       Console.WriteLine(result);
   }
}

Output:

False

In Throw, the original exception stack information is retained.

Example:

For Throw :

try

{
//  some operation that can fail
}
catch (Exception ex)
{
throw;
}

For Throw Ex:

In Throw Ex the original information is overridden by the External information and you will lose the original information.

try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw;
}

When we use indexers in class it behaves just like the virtual array. The user sets the value of the index and can retrieve the data without pointing an instance or a type member.

using System;
class clsIndexer  
{
   private string[] val = new string[3];  
   public string this[int index]  
   {
       get
       {
           return val[index];
       }
       set
       {
           val[index] = value;
       }
   }
}
class main {
   public static void Main() {
       clsIndexer ic = new clsIndexer();
       ic[0] = "C";
       ic[1] = "CPP";
       ic[2] = "CSHARP";
       Console.Write("Printing values stored in objects used as arrays\n");
       Console.WriteLine("First value = {0}", ic[0]);
       Console.WriteLine("Second value = {0}", ic[1]);
       Console.WriteLine("Third value = {0}", ic[2]);
   }
}
Property
Indexers
we can call any data member of the class directly
internal collection of an object can access its elements by using array notation on the object itself
class members can be accessed by a simple name
class members can be accessed through an index
get property doesn`t have parameters
get accessor of an indexer has the same parameter list as with the indexer
it can be static
it is not static

It is a powerful tool for determining the contents of unknown assembly which can be used for a wide variety of classes in simple words Reflection provides the ability to determine things and execute code at runtime.

Usage of Reflection:

  1. We can configure the application by loading the external configuration file and service based on it after doing this application don’t need to know about the classes that used those services till it conforms to a specific interface or API.
  2. Using Reflection we can generate the classes and code after which the programmer doesn`t need to rewrite all the code again.

The Namespace used for reflection is System.Reflection.

A ‘rectangular array’ is a multidimensional array where all the rows have the same number of elements, all elements are stored continuously in memory, these are very compact in memory example:

int[] arr = {1,2,4};
int[,] multiArr = new int[2,3];

A ‘jagged array’ is also known as an array of arrays. It is also the multidimensional array one in which the length of the rows need not be the same.

For example,

string[][] jaggedArray = new string[3][]{
   new string[] {"TeamCS", "John", "James", "Garry", "Linus"},
   new string[] {"TeamMath", "Ramanujan", "Hardy"},
   new string[] {"TeamSc", "Albert", "Tesla", "Newton"},
};

The above-jagged array consists of 3 rows, with each row having another array of different size. The elements in the jagged array are a reference of the other arrays, which can be anywhere in the memory

Web API
WCF
It is a web Application Programming Interface
It is a Windows Communication Foundation
It uses HTTP which is suitable for various protocols which support on various browser
Multiple protocols like: HTTP, HTTPS, Name Pipes, MSMQ,  etc., are supported and is allowed to switch between any of them
Web API   a simple class file with .cs (C#) extension
The Extension of WCF service is .svc
Web API support JSON or XML
It support JSON,XML,ATOM data format
It is not open source but it can be understood by the client who knows the Xml
If the client knows the XML then it doesn't meant for them

Expect to come across this popular question in ASP.NET technical interview questions.

Sessions are used in ASP.NET applications for state management. Sessions also make use of cookies to associate sessions with the correct user. But when browser cookies are turned off then in that case cookie-less sessions are used. It appends the values to the browser’s URL that is required to associate with the user.

By default sessions use a cookie in the background, to enable cookie-less sessions, the following settings are required to make in web.config file.

<sessionState cookieless="true" />

The possible options to set cookieless options  are:

  1. UseCookies: cookies are always used.
  2. UseUri: Instead of cookies, use the URL to store the session id
  3. UseDeviceProfile: Sessions uses cookies if the browser supports them, and else URL is used.
  4. AutoDetect: Session uses browser cookies if cookies are enabled. Else URL is used to store the session

Advantages of using session:

  • It helps us to maintain user state/data.
  • It is very easy to implement.
  • A session can store any kind of object in it. : Example: datatable, dataset... etc.
  • By using session we don't need to worry about data collapse because it stores every client data separately.
  • A session is secure and transparent from the user.
  • It is a global storage mechanism which helps in accessing the value from all pages in the web application
  • It is easy to use as session stores data in memory object of the current application domain.
  • It stores the client data separately so there is no worry about data collapse
  • It is secure and transparent from the user.
  • It can work in the multi-process configuration.
  • It always ensures data durability, since the session state retains the data even if the works process restart

ViewState is used to persist the data of page or page controls on postback. Viewstates are present on a page as a hidden field with data in an encrypted format. We can store any kind of data.

Advantages:

  1. Stored only at the client side, not on the server side.
  2. Since data in ViewState is always in encrypted form, hence secure.
  3. Viewstates can be enabled or disabled by viewstate properties.
  4. Viewstates can implement it at the page level or at the control level.

Disadvantages:

  1. If the size of viewstate data becomes large, then there might be a page load problem.
  2.   data is limited to the current page only, its information cannot be passed from one page to another.

Example:

public class Person
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
public partial class default : Web.UI.Pages
{
Person p = new Person();
p.FirstName = "Harshit";
p.LastName = "Mittal";
ViewState["PersonDetails"]=p;
}

Description

ASP.NET Core is a free and open-source framework that is widely adopted for its easy updates, high-speed performance, and command-line application that allows it to execute, create, and host several applications, easy maintenance, and cross-platform capabilities. It is a framework of the future, and there is a huge demand for professionals in this field. To learn more, you can join the best programming courses with KnowledgeHut to widen your horizons. 

Won’t a set of detailed FAQs boost your confidence to crack your ASP.NET interview? We have compiled a few questions and answers on ASP.NET, which will help you to showcase your knowledge to your employer on concepts that lie around it. The following interview questions for ASP.NET will surely help you to prepare and qualify for your ASP Net Core developer role. If you want to develop more knowledge and a firm base regarding ASP.NET, enroll in our Asp-Net Course and build your career's foundation.

Read More
Levels