0% found this document useful (0 votes)
26 views

Basic to advance ASP.Net Framework

Uploaded by

snehaandiyappan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Basic to advance ASP.Net Framework

Uploaded by

snehaandiyappan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Basic Level ASP.

NET Interview Questions

1. What is ASP.NET?

o ASP.NET is a web framework developed by Microsoft for building


dynamic web applications, websites, and web services. It is part
of the .NET framework.

2. Explain the difference between Web Forms and MVC in


ASP.NET.

o Web Forms: A traditional event-driven model for creating web


applications. It abstracts the stateless nature of the web.

o MVC (Model-View-Controller): A design pattern used to


separate an application into three interconnected components:
Model (data), View (UI), and Controller (logic). It provides more
control over the HTML output.

3. What is the Global.asax file in ASP.NET?

o The Global.asax file (also called the ASP.NET Application File)


contains code for application-level events such as
Application_Start, Application_End, Session_Start, etc. It is used
for global configuration and logic.

4. What is the difference between Session and ViewState in


ASP.NET?

o Session: Stores data on the server side. Data is available across


multiple pages and can persist until the session ends.

o ViewState: Stores data on the client-side, in a hidden field. It


persists across postbacks for a single page.

5. What is a Postback in ASP.NET?

o A Postback occurs when a page sends data to the server to be


processed and returns the result to the same page. This is
typically used in forms and controls.

6. What are the different types of validation controls in ASP.NET?

o RequiredFieldValidator: Ensures that a field is not empty.

o CompareValidator: Compares the value of two controls.


o RangeValidator: Ensures that the value falls within a specified
range.

o RegularExpressionValidator: Validates input using regular


expressions.

o CustomValidator: Validates input with a custom logic.

7. Explain the concept of Server Controls in ASP.NET.

o Server Controls are objects that allow you to create dynamic


content for web applications. These controls run on the server,
generate HTML dynamically, and send it to the browser.

Intermediate Level ASP.NET Interview Questions

1. What is the difference between Server.Transfer and


Response.Redirect in ASP.NET?

o Server.Transfer: Transfers the request to another page on the


server without changing the URL in the browser.

o Response.Redirect: Redirects the request to another page and


changes the URL in the browser.

2. Explain the concept of Master Pages in ASP.NET.

o Master Pages allow you to define a common layout (like headers,


footers) for multiple pages in an application. A Content Page can
reference a Master Page and override content sections.

3. What is the use of the Application object in ASP.NET?

o The Application object is used to store global data for all users in
an ASP.NET application. It is used in events such as
Application_Start and Application_End.

4. What is a Web.config file in ASP.NET?

o The Web.config file is an XML file used for configuring settings


related to the application, such as authentication, authorization,
connection strings, session state, custom error pages, and more.

5. What is the difference between Cache and Session in ASP.NET?


o Cache: Stores data globally for all users and for longer durations.
It improves performance by storing frequently used data.

o Session: Stores data for a specific user session. The data is user-
specific and is available until the session expires or the user logs
out.

6. What is the Page Life Cycle in ASP.NET?

o The ASP.NET Page Life Cycle consists of several stages such as


Page_Request, Page_Init, Page_Load, Page_PreRender,
Page_SaveState, and Page_Render, followed by Page_Unload.

7. What are HTTP Handlers and HTTP Modules in ASP.NET?

o HTTP Handler: A specialized class responsible for processing


specific HTTP requests (e.g., for image, text files).

o HTTP Module: A component that intercepts and processes HTTP


requests globally, allowing you to handle events like
authentication, logging, etc.

8. What is the difference between GET and POST methods in


ASP.NET?

o GET: Sends data to the server via the URL (query string). It is
less secure as data is visible in the URL.

o POST: Sends data in the body of the HTTP request. It is more


secure and used for large or sensitive data.

Advanced Level ASP.NET Interview Questions

1. Explain the concept of Dependency Injection (DI) in ASP.NET


Core.

o Dependency Injection is a design pattern used in ASP.NET Core to


inject dependencies into classes, rather than creating them
within the class. This promotes loose coupling and easier testing.

2. What is Middleware in ASP.NET Core?

o Middleware in ASP.NET Core is a component that processes HTTP


requests and responses. It is configured in the Startup.Configure
method and can be used for logging, authentication, error
handling, etc.

3. What is the difference between MVC and Web API in ASP.NET?

o MVC: A framework for building web applications with views (UI)


and controllers (logic).

o Web API: A framework for building HTTP services that are


accessible by clients, typically for RESTful services.

4. What are asynchronous actions in ASP.NET MVC?

o Asynchronous actions allow the application to handle long-


running requests (e.g., file upload, database queries) without
blocking the user interface. In MVC, this is achieved using async
and await.

5. Explain the Entity Framework in ASP.NET.

o Entity Framework is an Object-Relational Mapper (ORM) that


allows developers to interact with databases using .NET objects.
It supports code-first, database-first, and model-first approaches
for managing database schema.

6. What is SignalR in ASP.NET?

o SignalR is a real-time communication library in ASP.NET that


enables bi-directional communication between the server and
clients. It is commonly used for live notifications, chat
applications, and real-time updates.

7. What is the difference between IActionResult and ActionResult


in ASP.NET MVC?

o IActionResult: An interface that defines the contract for result


types in MVC actions (e.g., ViewResult, JsonResult).

o ActionResult: A concrete class implementing IActionResult,


which provides a default set of result types.

8. What are Attribute Routing and Conventional Routing in


ASP.NET Core?

o Attribute Routing: Defines routes using attributes on


controllers and actions (e.g., [Route("api/[controller]")]).
o Conventional Routing: Defines routes globally in the Startup.cs
file with predefined patterns (e.g., routes.MapRoute).

9. How can you implement Security in ASP.NET?

o ASP.NET provides multiple security measures, including:

 Authentication (Forms, Windows, OAuth, JWT)

 Authorization (Role-based, Claims-based)

 Encryption (Data protection API, SSL/TLS)

 Anti-CSRF (Cross-Site Request Forgery) tokens

 Secure cookies

10. What is the difference between ASP.NET Core and


ASP.NET MVC?

 ASP.NET Core: A cross-platform, open-source framework for building


web applications, APIs, and microservices.

 ASP.NET MVC: A framework for building web applications on the


Windows platform, based on the traditional .NET framework.

11. What are Caching Techniques in ASP.NET?

 ASP.NET provides multiple caching mechanisms:

o Output Caching: Stores the dynamic page's output for faster


response.

o Data Caching: Caches data (e.g., items from database queries).

o Application Caching: Caches data for the entire application.

o Distributed Caching: Stores data across multiple servers for


scalability.

12. Explain the role of async and await in ASP.NET Core.

 async and await are used for asynchronous programming in ASP.NET


Core. They allow long-running operations (e.g., database calls) to run
in the background without blocking the thread, improving performance
and scalability.

13. What is the difference between HttpClient and WebClient


in ASP.NET?
 HttpClient: A more modern, flexible, and powerful API for making
HTTP requests. It is ideal for use in asynchronous, non-blocking
scenarios.

 WebClient: An older, simpler class for making HTTP requests. It is less


flexible and does not support asynchronous operations in the same
way.

Here are answers with examples for each of the questions listed:

1. What is the difference between Web.config and Machine.config


files in ASP.NET?

 Web.config is a configuration file used for settings specific to a single


web application, such as security, database connections, and
application settings.

 Machine.config is a configuration file for the entire machine and


defines settings that apply globally to all ASP.NET applications on the
server.

Example:

 Web.config: Defines settings like authentication for one app.

 Machine.config: Defines server-wide settings like .NET framework


versions.

2. What is HttpContext in ASP.NET?

 HttpContext provides all HTTP-specific information about a request


and response, including request data, session state, and server
variables.

Example:

HttpContext.Current.Session["User"] = "JohnDoe";

3. What is a UserControl in ASP.NET?

 A UserControl is a reusable component that can be embedded within


a page. It is defined in a .ascx file and can be reused across multiple
pages.

Example:
<uc:MyControl runat="server" id="UserControl1" />

4. What is the difference between Request.Form and


Request.QueryString in ASP.NET?

 Request.Form retrieves data sent through HTTP POST.

 Request.QueryString retrieves data sent through HTTP GET.

Example:

 POST (Form):

 string username = Request.Form["username"];

 GET (Query String):

 string username = Request.QueryString["username"];

5. What is the difference between HttpRequest and HttpResponse in


ASP.NET?

 HttpRequest represents the client's request to the server, including


request headers, cookies, form data, etc.

 HttpResponse represents the server's response to the client, such as


sending content, setting cookies, and redirecting.

6. How do you handle errors in ASP.NET applications?

 Errors can be handled using try-catch blocks or custom error pages


(configured in web.config).

Example:

try

// Code that might throw an exception

catch (Exception ex)

Response.Redirect("ErrorPage.aspx");

}
7. What are the types of authentication in ASP.NET?

 Forms Authentication: Used for user authentication based on a login


form.

 Windows Authentication: Uses Windows credentials.

 Passport Authentication: Uses Microsoft Passport service.

 Custom Authentication: Custom solutions for authentication.

8. What is a cookie in ASP.NET?

 A cookie is a small piece of data stored on the client's browser to


maintain state across requests.

Example:

Response.Cookies["username"].Value = "JohnDoe";

9. What are the different types of session state modes in ASP.NET?

 InProc: Session is stored in memory on the web server.

 StateServer: Session is stored in a separate server.

 SQLServer: Session is stored in SQL Server.

 Custom: Custom session state management.

10. How do you set the session timeout in ASP.NET?

 You can set the session timeout in the web.config file or in the
Global.asax.

Example:

<system.web>

<sessionState timeout="20"></sessionState>

</system.web>

11. What is the purpose of Response.Write in ASP.NET?

 Response.Write is used to write output directly to the HTTP response,


which will be sent to the client.

Example:

Response.Write("Hello, world!");
12. What is the role of Session_Start and Session_End in the
Global.asax file?

 Session_Start: Occurs when a new session is created.

 Session_End: Occurs when a session expires or is abandoned.

Example:

void Session_Start(object sender, EventArgs e)

// Code to execute when a session starts

void Session_End(object sender, EventArgs e)

// Code to execute when a session ends

13. How do you store data in the Session object?

 Data can be stored in the Session object like a dictionary.

Example:

Session["User"] = "JohnDoe";

14. How would you check whether a user is authenticated in


ASP.NET?

 Use User.Identity.IsAuthenticated to check if the user is logged in.

Example:

if (User.Identity.IsAuthenticated)

// User is authenticated

15. What is the difference between Session and Cookies?

 Session: Data is stored on the server and is available throughout the


user's session.
 Cookies: Data is stored on the client (browser) and persists even after
the session ends.

16. What is the Application_Start event?

 Application_Start is triggered when the application starts (i.e., when


the first request is made).

Example:

void Application_Start(object sender, EventArgs e)

// Code to initialize application

17. What are Response.Redirect and Server.Transfer in ASP.NET


used for?

 Response.Redirect: Redirects the user to another page, making a


new request.

 Server.Transfer: Transfers the request to another page on the server


without making a new request.

Example:

Response.Redirect("AnotherPage.aspx");

18. What is the difference between the Visible and Enabled


properties of controls in ASP.NET?

 Visible: Controls whether the control is visible on the page.

 Enabled: Controls whether the user can interact with the control.

Example:

Button1.Visible = false;

Button1.Enabled = false;

19. How can you handle exceptions in ASP.NET?

 Use try-catch blocks or configure custom error pages in web.config.

20. What is the difference between Page_Load and Page_PreRender?


 Page_Load: Occurs when the page is loaded, but before the page is
fully rendered.

 Page_PreRender: Occurs just before the page's HTML is rendered.

Example:

void Page_Load(object sender, EventArgs e)

// Code for loading page

void Page_PreRender(object sender, EventArgs e)

// Code before page rendering

21. What is MasterPage in ASP.NET?

 A MasterPage defines a common layout for pages in a web


application. It provides a template for content pages.

Example:

<asp:ContentPlaceHolder ID="MainContent" runat="server" />

22. Explain the Page_Load event lifecycle.

 Page_Load is triggered when a page is loaded and before any controls


are rendered on the page. It allows for setting properties and data
binding.

23. What is the purpose of RunAt attribute in ASP.NET?

 The RunAt attribute is used to specify where the control should be


executed. The possible values are Server (default) and Client. It’s
generally used in declarative syntax.

Example:

<asp:Button runat="server" id="btnSubmit" Text="Submit" />

24. How do you implement custom server controls in ASP.NET?


 A custom server control is a control created from scratch to add
custom functionality, derived from System.Web.UI.Control.

Example:

public class CustomButton : Control

protected override void Render(HtmlTextWriter writer)

writer.Write("<button>Custom Button</button>");

25. What are Validators in ASP.NET and how do they work?

 Validators in ASP.NET are controls that validate user input on forms.


Examples include RequiredFieldValidator, RangeValidator, and
CompareValidator.

Example:

<asp:TextBox ID="txtEmail" runat="server" />

<asp:RequiredFieldValidator ControlToValidate="txtEmail" runat="server"


ErrorMessage="Email is required" />

26. What is a Literal control in ASP.NET?

 A Literal control displays static text on the page without any HTML
tags.

Example:

Literal literal = new Literal();

literal.Text = "Hello, world!";

form1.Controls.Add(literal);

27. What are the differences between HTML controls and Web
controls in ASP.NET?

 HTML Controls: Standard HTML elements such as <input> and


<button>.
 Web Controls: ASP.NET controls like <asp:Button> and
<asp:TextBox> that provide additional features such as event
handling.

Example:

 HTML control: <input type="text" />

 Web control: <asp:TextBox ID="txtName" runat="server" />

28. What are the differences between Inline and CodeBehind modes
of ASP.NET Web Forms?

 Inline: Code is written directly in the page’s markup.

 CodeBehind: Code is separated into a separate class file


(e.g., .aspx.cs).

Example:

 Inline: <%: Response.Write("Hello"); %>

 CodeBehind: Response.Write("Hello"); in the .aspx.cs file.

29. What is the role of App_Data folder in ASP.NET?

 The App_Data folder is used to store database files, XML files, and
other data files that should not be accessible to the client.

30. How do you create a simple form in ASP.NET?

 You create a form using ASP.NET controls like TextBox, Button, etc.,
and set the runat="server" attribute.

Example:

<form id="form1" runat="server">

<asp:TextBox ID="txtName" runat="server" />

<asp:Button ID="btnSubmit" runat="server" Text="Submit" />

</form>

31. What is GridView in ASP.NET? How do you bind data to it?

 A GridView is a data-bound control used to display data in a tabular


format.

Example:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="True" />

GridView1.DataSource = myDataSource;

GridView1.DataBind();

32. What are Repeater, DataList, and ListView controls? How are
they different from each other?

 Repeater: Displays data without built-in features like paging or


editing.

 DataList: Provides more formatting options and supports item editing.

 ListView: A more flexible control with support for templating and


customization.

Example:

<asp:Repeater ID="Repeater1" runat="server">

<ItemTemplate>

<p><%# Eval("Name") %></p>

</ItemTemplate>

</asp:Repeater>

33. What are Custom Controls and User Controls in ASP.NET? How
are they different?

 User Controls are reusable controls defined in .ascx files.

 Custom Controls are created programmatically and are more flexible


than user controls.

Example:

 User Control: <uc:MyControl runat="server" />

 Custom Control: A custom control derived from


System.Web.UI.Control.

34. What is ControlState in ASP.NET?

 ControlState is a mechanism that allows you to store data in the


control that is preserved across postbacks, even if the control is not
part of the page’s view state.
35. What is the difference between FindControl() and
GetPostBackControl() methods?

 FindControl() is used to find a control within the page hierarchy.

 GetPostBackControl() is used to detect the control that caused the


postback.

36. What is Caching in ASP.NET? Explain the types of caching.

 Caching is the process of storing data temporarily to improve


performance.

Types of Caching:

 Output Caching: Stores the entire page output.

 Data Caching: Stores objects like database queries.

 Application Caching: Stores application-level data.

Example:

HttpContext.Current.Cache["MyData"] = myData;

37. What is Output Caching in ASP.NET?

 Output Caching stores the result of a page or user control for


subsequent requests, reducing processing time.

Example:

[OutputCache(Duration = 60)]

public ActionResult Index() { return View(); }

38. How does the DataBinding work in ASP.NET?

 DataBinding allows controls to display data from a data source.

Example:

GridView1.DataSource = myDataSource;

GridView1.DataBind();

39. What is the difference between HTML Helpers and Standard


Controls in ASP.NET MVC?

 HTML Helpers are lightweight and create HTML markup.


 Standard Controls are full-fledged controls in WebForms.

Example:

 HTML Helper: @Html.TextBoxFor(model => model.Name)

 Standard Control: <asp:TextBox ID="txtName" runat="server" />

40. What are Route and Action filters in ASP.NET MVC?

 Route Filters: Apply logic during route matching.

 Action Filters: Apply logic before or after an action executes.

Example:

[ActionFilter]

public ActionResult Index() { return View(); }

41. What is ASP.NET MVC and how does it differ from Web Forms?

 ASP.NET MVC is a framework for building web applications based on


the MVC (Model-View-Controller) pattern. It offers more control over
HTML and URLs than Web Forms.

42. Explain the concept of Routing in ASP.NET MVC.

 Routing maps URLs to actions in the controller. The routes are defined
in RouteConfig.cs.

Example:

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller =


"Home", action = "Index", id = UrlParameter.Optional });

43. What is ActionResult in ASP.NET MVC? What are the different


types of ActionResult?

 ActionResult is the return type for actions in MVC controllers. It can


be different types, such as:

o ViewResult: Renders a view.

o RedirectResult: Redirects to another action.

o JsonResult: Returns JSON data.

Example:

public ActionResult Index() { return View(); }


44. What are ViewData, ViewBag, and TempData in ASP.NET MVC?
Explain the differences.

 ViewData: Stores data for the current request and is available in the
view.

 ViewBag: A dynamic wrapper around ViewData.

 TempData: Stores data that survives only until the next request.

Example:

ViewData["Message"] = "Hello";

ViewBag.Message = "Hello";

TempData["Message"] = "Hello";

45. What is Model Binding in ASP.NET MVC? How does it work?

 Model Binding is the process of mapping form values to model


properties automatically.

Example:

public ActionResult Create(Student student) { ... }

46. What is PartialView in ASP.NET MVC? When do you use it?

 A PartialView is a reusable view that can be rendered inside a parent


view. It is often used to render a part of the UI, such as a form or a list,
without reloading the entire page.

Example:

@Html.Partial("PartialViewName")

47. What is Dependency Injection in ASP.NET Core? Explain how it


works.

 Dependency Injection (DI) in ASP.NET Core is a design pattern used


to manage dependencies. It involves passing services (like database
contexts or custom services) to the controller or class constructor
rather than creating instances manually.

Example:

public class HomeController : Controller


{

private readonly IMyService _myService;

public HomeController(IMyService myService)

_myService = myService;

48. What are the differences between ASP.NET Core and ASP.NET
MVC?

 ASP.NET Core is a cross-platform, high-performance framework for


building web applications, while ASP.NET MVC is a web framework
based on the MVC pattern built on the .NET Framework. ASP.NET Core
is more lightweight, modular, and includes enhanced features like
Dependency Injection, improved routing, and is optimized for modern
web applications.

49. How does ASP.NET Core manage middleware?

 In ASP.NET Core, middleware components are configured in the


Startup.cs file and are executed in the order in which they are added to
the pipeline. Middleware handles requests and responses, such as
logging, authentication, and error handling.

Example:

public void Configure(IApplicationBuilder app)

app.UseAuthentication();

app.UseAuthorization();

50. What is Tag Helpers in ASP.NET Core MVC?

 Tag Helpers are a new feature in ASP.NET Core MVC that allow you to
use HTML-like syntax to interact with server-side code. They replace
the need for custom HTML helper methods.
Example:

<form asp-controller="Home" asp-action="Index">

<button type="submit">Submit</button>

</form>

51. What is the role of ConfigureServices and Configure methods in


Startup.cs in ASP.NET Core?

 ConfigureServices is used to add services to the dependency


injection container (e.g., add MVC, configure logging).

 Configure is used to set up the middleware pipeline, defining how


HTTP requests are handled (e.g., use authentication, static files,
routing).

Example:

public void ConfigureServices(IServiceCollection services)

services.AddControllersWithViews();

public void Configure(IApplicationBuilder app)

app.UseRouting();

app.UseEndpoints(endpoints => {

endpoints.MapControllerRoute(

name: "default",

pattern: "{controller=Home}/{action=Index}/{id?}");

});

52. How do you implement Authorization in ASP.NET Core?


 Authorization in ASP.NET Core is handled by adding policies or roles
in the ConfigureServices method and using attributes like [Authorize]
to restrict access to controllers or actions.

Example:

[Authorize(Roles = "Admin")]

public IActionResult AdminDashboard() { ... }

53. What is JWT (JSON Web Token) and how does it work in ASP.NET
Core?

 JWT is a compact, URL-safe token format for securely transmitting


information between parties. It is often used for authentication in
ASP.NET Core. The token is created during login and sent with requests
to authenticate users.

Example:

public string GenerateJwtToken(string username, IdentityUser user)

var claims = new[] {

new Claim(ClaimTypes.Name, username),

new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())

};

var key = new


SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]));

var creds = new SigningCredentials(key,


SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(

issuer: Configuration["Jwt:Issuer"],

audience: Configuration["Jwt:Audience"],

claims: claims,
expires: DateTime.Now.AddMinutes(30),

signingCredentials: creds);

return new JwtSecurityTokenHandler().WriteToken(token);

54. What is ASP.NET Core Identity?

 ASP.NET Core Identity is a set of APIs and tools for managing user
authentication, registration, and roles in an ASP.NET Core application.

55. How can you implement role-based authorization in ASP.NET


Core?

 Role-based authorization can be implemented by adding roles to users


during registration and then using the [Authorize(Roles = "RoleName")]
attribute to protect actions.

Example:

[Authorize(Roles = "Admin")]

public IActionResult AdminPage() { ... }

56. What is SignalR in ASP.NET Core?

 SignalR is a real-time communication framework that enables bi-


directional communication between the server and clients (e.g., web
browsers). It's commonly used for live updates, chat applications, or
real-time notifications.

Example:

public class ChatHub : Hub

public async Task SendMessage(string user, string message)

await Clients.All.SendAsync("ReceiveMessage", user, message);

}
57. What are the advantages of Web API over ASP.NET MVC?

 Web API is designed for creating RESTful services that return data
(usually in JSON or XML format), whereas ASP.NET MVC is optimized
for rendering HTML views. Web API is more suitable for mobile or
external application consumption.

58. How do you secure Web API in ASP.NET Core?

 Web API security can be implemented using OAuth, JWT tokens, or


API Keys for authentication and authorization.

59. How can you implement OAuth and OpenID authentication in


ASP.NET Core?

 OAuth and OpenID Connect can be integrated with ASP.NET Core using
authentication middleware, typically with an external provider like
Google, Facebook, or custom identity providers.

Example:

services.AddAuthentication()

.AddOAuth("GitHub", options =>

options.ClientId = Configuration["GitHub:ClientId"];

options.ClientSecret = Configuration["GitHub:ClientSecret"];

});

60. What are ASP.NET Core Razor Pages? How do they differ from
MVC?

 Razor Pages is a page-based programming model in ASP.NET Core.


Unlike MVC, which separates concerns into controllers and views, Razor
Pages focuses on the page itself, with the logic and view combined into
a single file (e.g., .cshtml).

61. How do you manage the state in an ASP.NET application?

 State management in ASP.NET can be handled in several ways:

o Client-Side: Cookies, Query Strings, Local Storage.

o Server-Side: Session, Application State, or databases.


62. What is the difference between conventional routing and
attribute routing in ASP.NET Core?

 Conventional Routing uses a centralized route configuration in


Startup.cs for defining routes.

 Attribute Routing uses attributes on controllers and actions to define


routes directly.

Example of Attribute Routing:

[Route("home/index")]

public IActionResult Index() { return View(); }

63. Explain the concept of action filters in ASP.NET MVC.

 Action Filters are used to execute custom logic before or after an


action method runs. Common examples include logging,
authentication, and authorization.

Example:

public class MyActionFilter : ActionFilterAttribute

public override void OnActionExecuting(ActionExecutingContext context)

// Custom logic before the action is executed

base.OnActionExecuting(context);

64. What are Asynchronous Controllers in ASP.NET MVC? How do


they work?

 Asynchronous controllers handle long-running operations (e.g.,


database queries) without blocking the thread, improving performance
by using async and await.

Example:

public async Task<ActionResult> GetData()


{

var data = await GetDataFromDatabaseAsync();

return View(data);

65. What is Task Parallel Library (TPL) and how is it used in ASP.NET
applications?

 TPL is a set of APIs in .NET for parallel programming. It simplifies multi-


threading by allowing tasks to run concurrently.

Example:

Task.Run(() => DoWork());

66. Explain the purpose of IActionResult and its types in ASP.NET


MVC.

 IActionResult is the return type for MVC controller actions. Different


implementations of IActionResult include:

o ViewResult: Returns a view.

o RedirectResult: Redirects to another action.

o JsonResult: Returns JSON data.

67. How do you handle Versioning in ASP.NET Core Web API?

 Versioning in ASP.NET Core Web API can be implemented using query


parameters, URL path versioning, or headers. A common approach is to
use the Microsoft.AspNetCore.Mvc.Versioning package for
versioning your APIs.

Example:

services.AddApiVersioning(options =>

options.ReportApiVersions = true;

});

In the controller, you can specify versions as:

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]

public class ProductsController : ControllerBase

// Action methods here

68. How do you configure exception handling globally in ASP.NET


Core?

 Global exception handling in ASP.NET Core can be done by adding


middleware in the Configure method in the Startup.cs file using
UseExceptionHandler for production environments.

Example:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

if (env.IsDevelopment())

app.UseDeveloperExceptionPage();

else

app.UseExceptionHandler("/Home/Error");

app.UseHsts();

69. What is the difference between Thread and Task in ASP.NET?

 A Thread is a basic unit of execution in a process, whereas a Task is a


higher-level abstraction that is used to manage asynchronous
operations. Tasks are more efficient because they are part of the Task
Parallel Library (TPL) and are designed to handle operations
asynchronously without manually managing threads.
Example of Task:

public async Task<IActionResult> GetDataAsync()

var data = await _dataService.GetDataAsync();

return Ok(data);

70. What is the role of Data Annotations in ASP.NET MVC?

 Data Annotations are used for model validation in ASP.NET MVC.


These annotations can specify rules for validation, such as required
fields, maximum length, range, etc.

Example:

public class UserModel

[Required]

[StringLength(50)]

public string Username { get; set; }

[EmailAddress]

public string Email { get; set; }

71. How do you prevent Cross-Site Scripting (XSS) attacks in


ASP.NET?

 To prevent XSS attacks, use HTML encoding for user input, such as
using @Html.Encode() or @Html.Raw() for rendering user-generated
content safely. Additionally, ASP.NET MVC's default HTML helpers
automatically encode output.

Example:

<div>@Html.Encode(userInput)</div>
You can also enable CSP (Content Security Policy) headers to prevent
malicious scripts.

72. What is ModelState.IsValid in ASP.NET MVC?

 ModelState.IsValid is a property that checks whether the model passed


to the controller is valid according to the data annotations or custom
validation logic defined in the model.

Example:

if (ModelState.IsValid)

// Process the data

else

// Return the view with validation errors

return View(model);

73. Explain the role of IHttpContextAccessor in ASP.NET Core.

 IHttpContextAccessor is used to access the current HttpContext in


scenarios where it is not directly available, such as in services or
classes not directly tied to HTTP requests.

Example:

public class MyService

private readonly IHttpContextAccessor _httpContextAccessor;

public MyService(IHttpContextAccessor httpContextAccessor)

_httpContextAccessor = httpContextAccessor;
}

public string GetCurrentRequestUrl()

return _httpContextAccessor.HttpContext.Request.Path.ToString();

74. What is Attribute Routing and how is it implemented in ASP.NET


Core?

 Attribute Routing allows you to define routes directly on the


controller or action methods using attributes, rather than configuring
routes globally. This provides more control and flexibility.

Example:

[Route("api/[controller]")]

public class ProductsController : ControllerBase

[HttpGet]

public IActionResult GetAllProducts()

// Retrieve products

return Ok(products);

[HttpGet("{id}")]

public IActionResult GetProductById(int id)

// Retrieve product by id

return Ok(product);
}

75. How do you create Custom Validation Attributes in ASP.NET


MVC?

 Custom validation attributes can be created by inheriting from


ValidationAttribute and overriding the IsValid method to implement
custom validation logic.

Example:

public class CustomEmailValidationAttribute : ValidationAttribute

public override bool IsValid(object value)

var email = value as string;

if (string.IsNullOrEmpty(email)) return false;

return email.Contains("@") && email.Contains(".");

76. How does Entity Framework (EF) Core support migrations?

 EF Core migrations allow you to manage schema changes to the


database in a versioned manner. Migrations can be added, updated,
and applied to the database using the dotnet ef CLI tools or the
Package Manager Console in Visual Studio.

Example of adding a migration:

dotnet ef migrations add InitialCreate

dotnet ef database update

77. How can you implement Caching in ASP.NET Core?


 Caching can be implemented in ASP.NET Core using memory caching,
distributed caching, or response caching. For example, you can use the
IMemoryCache interface to store data in memory.

Example:

public class MyController : Controller

private readonly IMemoryCache _cache;

public MyController(IMemoryCache cache)

_cache = cache;

public IActionResult GetCachedData()

if (!_cache.TryGetValue("myData", out string myData))

myData = "This is cached data!";

_cache.Set("myData", myData, TimeSpan.FromMinutes(1));

return Ok(myData);

78. Explain the role of Dependency Injection in ASP.NET Core and


provide examples.

 Dependency Injection (DI) in ASP.NET Core allows services and


objects to be injected into classes through their constructors, making
the application more modular, testable, and maintainable.
Example:

public class HomeController : Controller

private readonly IMyService _myService;

public HomeController(IMyService myService)

_myService = myService;

public IActionResult Index()

var data = _myService.GetData();

return View(data);

79. What is IConfiguration in ASP.NET Core and how is it used to


manage app settings?

 IConfiguration is an interface in ASP.NET Core that provides a way to


access application settings from various sources like JSON files,
environment variables, and command-line arguments.

Example:

// appsettings.json

"MySettings": {

"ConnectionString": "Server=myserver;Database=mydb;"

}
public class MyService

private readonly IConfiguration _configuration;

public MyService(IConfiguration configuration)

_configuration = configuration;

public string GetConnectionString()

return _configuration["MySettings:ConnectionString"];

80. How do you implement Custom Middlewares in ASP.NET Core?

 Custom middleware can be implemented by creating a class with a


constructor that accepts RequestDelegate and an Invoke method that
processes HTTP requests.

Example:

public class CustomMiddleware

private readonly RequestDelegate _next;

public CustomMiddleware(RequestDelegate next)

_next = next;

}
public async Task InvokeAsync(HttpContext context)

// Custom logic before request

await _next(context);

// Custom logic after request

public void Configure(IApplicationBuilder app)

app.UseMiddleware<CustomMiddleware>();

Here are the answers for the remaining questions:

81. What are the different ways to handle background tasks in


ASP.NET Core?

 Background tasks in ASP.NET Core can be handled using the


IHostedService interface, BackgroundService class, or third-party
libraries like Hangfire. These methods allow tasks to run in the
background without blocking the main application.

Example with BackgroundService:

public class MyBackgroundService : BackgroundService

protected override async Task ExecuteAsync(CancellationToken


stoppingToken)

while (!stoppingToken.IsCancellationRequested)
{

// Background task logic

await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);

public void ConfigureServices(IServiceCollection services)

services.AddHostedService<MyBackgroundService>();

82. How do you implement Custom Model Binding in ASP.NET Core?

 Custom model binding can be implemented by creating a class that


implements IModelBinder and handling the binding logic.

Example:

public class CustomDateBinder : IModelBinder

public Task BindModelAsync(ModelBindingContext bindingContext)

var value = bindingContext.ValueProvider.GetValue("date").FirstValue;

if (DateTime.TryParse(value, out DateTime date))

bindingContext.Result = ModelBindingResult.Success(date);

else

{
bindingContext.ModelState.AddModelError("date", "Invalid date
format");

return Task.CompletedTask;

public void ConfigureServices(IServiceCollection services)

services.AddControllers(options =>

options.ModelBinderProviders.Insert(0, new
CustomModelBinderProvider());

});

83. What is Session state and how is it used in ASP.NET Core?

 Session state is used to store and retrieve user data across multiple
requests during a user session. In ASP.NET Core, session state can be
managed using ISession.

Example:

public class HomeController : Controller

public IActionResult Index()

HttpContext.Session.SetString("Username", "JohnDoe");

return View();

}
public IActionResult GetUsername()

var username = HttpContext.Session.GetString("Username");

return Content(username);

public void ConfigureServices(IServiceCollection services)

services.AddDistributedMemoryCache();

services.AddSession(options =>

options.IdleTimeout = TimeSpan.FromMinutes(30);

});

public void Configure(IApplicationBuilder app)

app.UseSession();

84. What is Distributed Caching in ASP.NET Core? How is it


implemented?

 Distributed caching stores cached data in an external store (like


Redis or SQL Server) instead of in-memory to provide cache sharing
across multiple instances of an application.

Example with Redis:

public void ConfigureServices(IServiceCollection services)

{
services.AddStackExchangeRedisCache(options =>

options.Configuration = "localhost:6379";

options.InstanceName = "SampleApp:";

});

public class HomeController : Controller

private readonly IDistributedCache _cache;

public HomeController(IDistributedCache cache)

_cache = cache;

public async Task<IActionResult> GetCacheData()

var cachedData = await _cache.GetStringAsync("myData");

if (string.IsNullOrEmpty(cachedData))

cachedData = "This is new cached data";

await _cache.SetStringAsync("myData", cachedData);

return Ok(cachedData);

}
85. How do you enable HTTPS in an ASP.NET Core application?

 In ASP.NET Core, HTTPS can be enabled using the


UseHttpsRedirection() middleware, which redirects HTTP requests to
HTTPS, and by configuring the server to listen on HTTPS.

Example:

public void Configure(IApplicationBuilder app)

app.UseHttpsRedirection();

app.UseRouting();

app.UseEndpoints(endpoints =>

endpoints.MapControllers();

});

public void ConfigureServices(IServiceCollection services)

services.AddHttpsRedirection(options =>

options.HttpsPort = 5001;

});

86. What is the role of WebSocket in ASP.NET Core?

 WebSocket is a protocol that provides full-duplex communication


channels over a single TCP connection. In ASP.NET Core, WebSocket
support can be used for real-time communication between clients and
servers, such as chat applications.

Example:
public void Configure(IApplicationBuilder app)

app.UseWebSockets();

app.Use(async (context, next) =>

if (context.WebSockets.IsWebSocketRequest)

var webSocket = await


context.WebSockets.AcceptWebSocketAsync();

await HandleWebSocketAsync(webSocket);

else

await next();

});

private async Task HandleWebSocketAsync(WebSocket webSocket)

var buffer = new byte[1024 * 4];

var result = await webSocket.ReceiveAsync(new


ArraySegment<byte>(buffer), CancellationToken.None);

while (!result.CloseStatus.HasValue)

await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0,


result.Count), result.MessageType, result.EndOfMessage,
CancellationToken.None);
result = await webSocket.ReceiveAsync(new
ArraySegment<byte>(buffer), CancellationToken.None);

await webSocket.CloseAsync(result.CloseStatus.Value,
result.CloseStatusDescription, CancellationToken.None);

87. Explain the OAuth2 flow in ASP.NET Core.

 OAuth2 is a protocol for authorization. It allows a user to grant a third-


party application limited access to their resources without exposing
their credentials. The flow typically involves authorization, redirection,
and token exchange.

OAuth2 Flow Example:

1. User logs in through a third-party service (e.g., Google, Facebook).

2. Authorization code is returned to the app.

3. Access token is obtained using the authorization code.

4. The app uses the access token to make API calls on behalf of the user.

Example in ASP.NET Core with OAuth2 Authentication:

public void ConfigureServices(IServiceCollection services)

services.AddAuthentication(options =>

options.DefaultScheme =
CookieAuthenticationDefaults.AuthenticationScheme;

options.DefaultChallengeScheme =
GoogleDefaults.AuthenticationScheme;

})

.AddCookie()

.AddGoogle(options =>

{
options.ClientId = Configuration["Google:ClientId"];

options.ClientSecret = Configuration["Google:ClientSecret"];

});

88. How do you implement RESTful APIs in ASP.NET Core?

 RESTful APIs in ASP.NET Core can be implemented using the MVC


pattern, with controllers and actions corresponding to HTTP methods
(GET, POST, PUT, DELETE).

Example:

[ApiController]

[Route("api/[controller]")]

public class ProductsController : ControllerBase

[HttpGet]

public IActionResult GetAllProducts()

// Return all products

return Ok(products);

[HttpPost]

public IActionResult CreateProduct(Product product)

// Create a new product

return CreatedAtAction(nameof(GetProduct), new { id = product.Id },


product);

}
[HttpGet("{id}")]

public IActionResult GetProduct(int id)

// Retrieve a product by ID

return Ok(product);

89. How do you log exceptions and events in ASP.NET Core using
ILogger?

 ILogger is used in ASP.NET Core to log errors, events, and other


diagnostic information. It supports different log levels, such as
Information, Warning, Error, etc.

Example:

public class HomeController : Controller

private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)

_logger = logger;

public IActionResult Index()

_logger.LogInformation("User accessed the Index page.");

try

// Some code that might throw an exception


}

catch (Exception ex)

_logger.LogError(ex, "An error occurred while processing the


request.");

return View();

90. What is ActionResult in ASP.NET Core Web API?

 ActionResult is a return type used in ASP.NET Core Web API to return


both an HTTP status code and a data result. This allows flexibility for
returning different status codes and responses.

Example:

public ActionResult<Product> GetProduct(int id)

var product = _productService.GetProductById(id);

if (product == null)

return NotFound();

return Ok(product);

Here are the answers for the remaining questions from your list:

91. How do you implement Swagger for API documentation in


ASP.NET Core?

 Swagger is used for API documentation in ASP.NET Core. You can use
the Swashbuckle.AspNetCore package to generate Swagger UI for
your API.
Steps to implement:

1. Install the Swashbuckle package:

2. dotnet add package Swashbuckle.AspNetCore

3. In Startup.cs or Program.cs, add Swagger services in


ConfigureServices:

4. public void ConfigureServices(IServiceCollection services)

5. {

6. services.AddSwaggerGen();

7. services.AddControllers();

8. }

9. In the Configure method, add Swagger middleware:

10. public void Configure(IApplicationBuilder app,


IWebHostEnvironment env)

11. {

12. app.UseSwagger();

13. app.UseSwaggerUI(c =>

14. {

15. c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API


V1");

16. });

17. }

92. How can you scale a web application in ASP.NET Core?

 Scaling a web application can be done in two main ways: vertically


(increasing resources on the server) or horizontally (adding more
servers).

o Vertical Scaling: Increase the capacity of the server (CPU,


RAM).

o Horizontal Scaling: Deploy the application on multiple servers


and use a load balancer to distribute traffic.
o Additionally, use techniques like caching, database
optimization, distributed systems, and CDNs for better
performance.

o Tools like Azure App Services, Kubernetes, or Docker can


also help with scaling.

93. How do you integrate Serilog for logging in ASP.NET Core?

 Serilog is a structured logging library that you can integrate into


ASP.NET Core for advanced logging features.

Steps to integrate Serilog:

1. Install the Serilog NuGet packages:

2. dotnet add package Serilog.AspNetCore

3. dotnet add package Serilog.Sinks.Console

4. In Program.cs, configure Serilog:

5. using Serilog;

6.

7. public class Program

8. {

9. public static void Main(string[] args)

10. {

11. Log.Logger = new LoggerConfiguration()

12. .WriteTo.Console()

13. .CreateLogger();

14.

15. CreateHostBuilder(args).Build().Run();

16. }

17.

18. public static IHostBuilder CreateHostBuilder(string[] args) =>

19. Host.CreateDefaultBuilder(args)
20. .UseSerilog() // Use Serilog for logging

21. .ConfigureWebHostDefaults(webBuilder =>

22. {

23. webBuilder.UseStartup<Startup>();

24. });

25. }

94. What are Filters in ASP.NET Core? Explain Action Filters, Result
Filters, and Exception Filters.

 Filters in ASP.NET Core allow you to add logic before and after actions
or results are processed. The main types of filters are:

o Action Filters: Run before or after an action method executes.


Used to modify input parameters or handle actions like logging.

o public class MyActionFilter : IActionFilter

o {

o public void OnActionExecuting(ActionExecutingContext


context)

o {

o // Code before the action executes

o }

o public void OnActionExecuted(ActionExecutedContext context)

o {

o // Code after the action executes

o }

o }

o Result Filters: Run before or after the action result executes.


Used for modifying the result, such as adding headers.

o public class MyResultFilter : IResultFilter


o {

o public void OnResultExecuting(ResultExecutingContext


context)

o {

o // Code before the result executes

o }

o public void OnResultExecuted(ResultExecutedContext context)

o {

o // Code after the result executes

o }

o }

o Exception Filters: Catch and handle exceptions that occur


during action execution.

o public class MyExceptionFilter : IExceptionFilter

o {

o public void OnException(ExceptionContext context)

o {

o // Handle exception

o context.ExceptionHandled = true;

o }

o }

95. How do you optimize database queries in Entity Framework in


ASP.NET Core?

 To optimize database queries in Entity Framework (EF) Core:

o Use AsNoTracking for read-only queries to improve


performance.

o Eager Loading: Use Include to load related data.


o Lazy Loading: Enable lazy loading, but use it cautiously to avoid
excessive queries.

o Batch Queries: Use FromSqlRaw or ExecuteSqlRaw for


executing complex SQL.

o Indexes: Ensure the database has proper indexes on frequently


queried fields.

Example:

var products = dbContext.Products.AsNoTracking().Where(p => p.Price >


100).ToList();

96. What is Connection Pooling and how does it improve


performance in ASP.NET applications?

 Connection Pooling helps in reusing database connections instead of


creating a new connection each time a request is made. This improves
performance by reducing the overhead of opening and closing
connections frequently.

 Entity Framework and ADO.NET automatically use connection


pooling when connecting to databases like SQL Server.

97. How do you handle concurrent requests in ASP.NET Core?

 ASP.NET Core handles concurrent requests by default. The framework


uses asynchronous programming models with async and await
keywords to handle multiple requests concurrently without blocking the
thread.

 Concurrency can be controlled by using locking mechanisms (like


lock, semaphores) when dealing with shared resources.

98. What is the difference between Web API and gRPC in ASP.NET
Core?

 Web API is an HTTP-based communication framework for building


RESTful services.

 gRPC is a high-performance, open-source RPC framework that uses


HTTP/2 and Protocol Buffers for serialization. It provides better
performance and supports bi-directional streaming, making it more
suitable for microservices and high-performance scenarios.

99. How do you handle large file uploads in ASP.NET Core?


 ASP.NET Core allows you to upload large files by configuring file size
limits and handling multipart form data.

o Set the file upload size limit in Startup.cs:

o public void ConfigureServices(IServiceCollection services)

o {

o services.Configure<FormOptions>(options =>

o {

o options.MultipartBodyLengthLimit = 104857600; // 100 MB

o });

o }

o Use IFormFile to handle file uploads:

o [HttpPost]

o public async Task<IActionResult> UploadFile(IFormFile file)

o {

o if (file.Length > 0)

o {

o var filePath = Path.Combine("uploads", file.FileName);

o using (var stream = new FileStream(filePath,


FileMode.Create))

o {

o await file.CopyToAsync(stream);

o }

o return Ok(new { FilePath = filePath });

o }

o return BadRequest("No file uploaded");

o }

100. What are Health Checks in ASP.NET Core and how do you
implement them?
 Health Checks allow you to check the health of your application and
its dependencies (like databases, services). ASP.NET Core provides
built-in middleware to monitor application health.

Steps to implement:

1. Install the required NuGet package:

2. dotnet add package Microsoft.AspNetCore.Diagnostics.HealthChecks

3. In Startup.cs, configure the health checks:

4. public void ConfigureServices(IServiceCollection services)

5. {

6. services.AddHealthChecks();

7. }

8.

9. public void Configure(IApplicationBuilder app)

10. {

11. app.UseHealthChecks("/health");

12. }

101. What is the difference between Thread and Task in ASP.NET?

 Thread: Represents a unit of work in a system, each running


concurrently. Managing threads directly can be more complex and
resource-intensive.

 Task: Represents an asynchronous operation that can run in the


background. It's part of the Task Parallel Library (TPL) and is
managed by the .NET runtime, making it more lightweight and easier
to use for parallel execution.

You might also like