| ASP.NET Interview Questions 31 to 40 :👈 | 👉:EF: ObjectContext and DbContext |
ASP.NET Interview Questions 41 to 50 |
41. What is the role of a controller in an MVC application?
A controller handles incoming requests, coordinates application behavior, and determines the response returned to the client.
Its responsibilities commonly include:
- Receiving requests routed to its action methods.
- Accepting and validating input.
- Calling business services to perform application operations.
- Selecting a view or another appropriate response.
- Returning results such as views, JSON, files, or redirects.
Example:
public class ProductController : Controller
{
public ActionResult Details(int id)
{
// A real application would retrieve the product
// through an application service.
ViewBag.ProductId = id;
return View();
}
}
A controller should generally remain thin. Business rules belong in appropriate application or domain services rather than being embedded in large controller methods.
42. What is the significance of NonActionAttribute?
The [NonAction] attribute indicates that a public controller method must not be treated as an MVC action method.
Example:
public class HomeController : Controller
{
public ActionResult Index()
{
string message = GetMessage();
return Content(message);
}
[NonAction]
public string GetMessage()
{
return "Welcome to MVC";
}
}
Here, GetMessage() can be called by the controller's own code, but MVC does not expose it as an action method through normal action discovery.
Important: [NonAction] is not a complete security boundary. Sensitive operations must still be protected by appropriate authorization and application design.
43. What is the use of the following default route?
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
This route defines a conventional URL pattern for an ASP.NET MVC application.
name: "Default"gives the route a name.{controller}represents the controller segment.{action}represents the action segment.{id}represents an optional parameter.controller = "Home"supplies the default controller.action = "Index"supplies the default action.id = UrlParameter.Optionalallows the ID segment to be omitted.
Examples:
| URL | Controller | Action | ID |
|---|---|---|---|
/ |
Home | Index | Not supplied |
/Home/About |
Home | About | Not supplied |
/Product/Details/10 |
Product | Details | 10 |
44. What is URL Munging?
URL munging is the process of modifying a URL to include additional information or to adapt it to a particular application requirement.
In older ASP.NET discussions, the term is often associated with URL-based session state, where a session identifier is embedded in the URL when cookies are unavailable or disabled.
Example of a URL containing a session-related identifier:
/MyApplication/(S(session-id))/Products
The exact URL format depends on the ASP.NET configuration and session-state mode.
Embedding session identifiers in URLs can expose them through browser history, logs, screenshots, and referrer information. Cookies or other appropriately designed session mechanisms are generally preferable.
45. When running an ASP.NET component, which process hosts it on Windows XP, Windows 2000, and Windows Server 2003?
For classic ASP.NET applications hosted in IIS, the traditional answer depends on the IIS version and process-isolation configuration.
| Operating System | Typical ASP.NET Worker Process | Notes |
|---|---|---|
| Windows 2000 | aspnet_wp.exe |
IIS 5-era ASP.NET hosting commonly used this process. |
| Windows XP | aspnet_wp.exe |
IIS 5.1 commonly used the ASP.NET worker process. |
| Windows Server 2003 | w3wp.exe or aspnet_wp.exe |
IIS 6 commonly used w3wp.exe in worker-process isolation mode. Legacy configurations could use different hosting arrangements. |
Interview point: aspnet_wp.exe is associated with older IIS hosting, while w3wp.exe is the IIS worker process used in IIS 6 and later.
46. Where are routing rules defined in an ASP.NET MVC application?
In a typical ASP.NET MVC 5 application, routing rules are defined in:
App_Start/RouteConfig.cs
The routes are registered at application startup in Global.asax:
RouteConfig.RegisterRoutes(RouteTable.Routes);
Individual areas can also define their own routes in their area registration classes. Route order matters because routes are generally evaluated in registration order.
ASP.NET Core applications use a different routing configuration approach, typically involving endpoint mapping in Program.cs or related startup configuration.
47. Which approach provides better support for test-driven development: ASP.NET MVC or ASP.NET Web Forms?
ASP.NET MVC generally provides better support for test-driven development (TDD) than traditional ASP.NET Web Forms.
Reasons include:
- Separation of concerns: MVC separates controllers, models, and views.
- Testable controllers: Controllers can be tested independently of the view-rendering process.
- Explicit request handling: Action methods make request and response behavior easier to reason about.
- Dependency injection: Controllers can use injected services and test doubles.
- Less dependence on the page lifecycle: MVC does not rely on the same Web Forms page lifecycle and ViewState model.
Web Forms applications can also be tested, but their event-driven page lifecycle and tighter coupling to the framework can make some forms of unit testing more difficult.
48. Is the [ThreadStatic] Attribute Useful in ASP.NET? Are There Side Effects? Is It Good or Bad?
The [ThreadStatic] attribute in .NET marks a static field so that each operating-system thread has its own separate value for that field.
Example
using System;
public class RequestContext
{
[ThreadStatic]
public static string UserName;
}
If two threads assign different values to RequestContext.UserName, each thread sees its own value rather than sharing a single value across all threads.
Is It Useful in ASP.NET?
It can be useful in limited scenarios where data genuinely belongs to a specific thread. However, it is generally unsuitable for storing ASP.NET request-specific data.
Problems and Side Effects
- Thread reuse: ASP.NET reuses worker threads to process different requests. A thread-static value can remain set after one request finishes and accidentally affect a later request on the same thread.
- Asynchronous execution: An asynchronous operation may resume on a different thread. A thread-static value does not automatically follow the logical request across threads.
- Initialization: A static field initializer does not initialize a separate value for every thread in the way developers may expect. A thread's value may initially be the type's default value.
- Testing difficulty: Thread-dependent state can make code harder to test and reason about.
- Concurrency assumptions: Thread-local values do not automatically provide safe shared state or request isolation.
Better Alternatives
| Requirement | Recommended Approach |
|---|---|
| Request-specific information in classic ASP.NET | HttpContext.Items |
| Request-specific information in ASP.NET Core | Scoped services or HttpContext.Items, depending on the requirement |
| Data that must flow with asynchronous execution | AsyncLocal<T>, used carefully |
| Application-wide shared data | A properly designed singleton or shared service with suitable concurrency controls |
Example using HttpContext.Items in classic ASP.NET MVC:
public ActionResult Index()
{
HttpContext.Items["UserName"] = "John";
string userName =
HttpContext.Items["UserName"] as string;
return Content(userName ?? "Unknown");
}
HttpContext.Items stores data for the current request and is generally a better fit for request-specific information.
Interview conclusion: [ThreadStatic] is not inherently bad, but it is usually the wrong choice for request-scoped data in ASP.NET. Prefer request-scoped mechanisms or explicitly propagated state.
49. Briefly Explain the Usage of Global.asax
Global.asax, also known as the ASP.NET application file, is used in classic ASP.NET applications to handle application-level and session-level events.
It is commonly used to configure routes, register application components, initialize application-wide resources, and implement centralized error handling.
Common Uses
- Application_Start: Runs when the ASP.NET application starts.
- Application_End: Runs when the application is shutting down normally.
- Session_Start: Runs when a new session begins.
- Session_End: Runs when a session ends in supported session-state configurations, such as InProc.
- Application_Error: Handles unhandled application errors at the application level.
- Application_BeginRequest: Runs at the beginning of each request.
Example Global.asax
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Register MVC routes.
RouteConfig.RegisterRoutes(
System.Web.Routing.RouteTable.Routes);
}
void Session_Start(object sender, EventArgs e)
{
// Initialize session-specific information if needed.
}
void Application_Error(object sender, EventArgs e)
{
// Log unhandled application errors securely.
}
</script>
In an MVC 5 project, Global.asax commonly calls registration methods for routes, filters, and bundles.
Important: Application startup can occur again after an application restart or recycle. Do not assume that Application_Start runs exactly once for the lifetime of the server. Also, Session_End is not supported for every session-state mode.
ASP.NET Core difference: ASP.NET Core does not use Global.asax. Startup configuration and middleware are normally configured through Program.cs and the application's hosting model.
50. What Is Minification?
Minification is the process of reducing the size of HTML, CSS, and JavaScript files by removing unnecessary characters, such as whitespace, comments, and line breaks, without changing the code's functionality.
It helps websites load faster by reducing the amount of data transferred from the server to the browser.
1. Example of JavaScript Minification
Before Minification
// Calculate the total price
function calculateTotal(price, quantity) {
let total = price * quantity;
return total;
}
console.log(calculateTotal(100, 2));
After Minification
function calculateTotal(price,quantity){let total=price*quantity;return total}console.log(calculateTotal(100,2));
Both versions perform the same operation, but the minified version removes unnecessary whitespace and comments.
2. Example of CSS Minification
Before Minification
/* Main heading */
h1 {
color: blue;
font-size: 24px;
margin-bottom: 10px;
}
After Minification
h1{color:blue;font-size:24px;margin-bottom:10px}
3. Example of HTML Minification
Before Minification
<div>
<h2>Welcome</h2>
<p>Welcome to our website.</p>
</div>
After Minification
<div><h2>Welcome</h2><p>Welcome to our website.</p></div>
Note: HTML minification requires care because whitespace can affect the appearance or behavior of certain elements.
4. Advantages of Minification
- Faster page loading: Reduces the amount of data downloaded by the browser.
- Reduced bandwidth: Transfers fewer bytes between the server and browser.
- Improved performance: Can improve page-loading performance, especially on slower connections.
- Lower transfer costs: May reduce bandwidth usage for high-traffic websites.
5. Minification vs. Bundling vs. Compression
| Technique | Purpose | Example |
|---|---|---|
| Minification | Removes unnecessary characters from source files. | site.css becomes site.min.css. |
| Bundling | Combines multiple files into one file. | header.css and footer.css become bundle.css. |
| Compression | Compresses response data during transfer. | Gzip or Brotli reduces the transmitted size. |
These techniques can be used together to optimize website performance.
6. How to Minify Files in ASP.NET MVC
In ASP.NET MVC 5, you can use the System.Web.Optimization package to bundle and minify CSS and JavaScript files.
Example: BundleConfig.cs
using System.Web.Optimization;
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/scripts")
.Include(
"~/Scripts/jquery.js",
"~/Scripts/site.js"
));
bundles.Add(new StyleBundle("~/Content/css")
.Include(
"~/Content/site.css",
"~/Content/custom.css"
));
}
}
Register Bundles in Global.asax
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Reference Bundles in a Razor View
@Scripts.Render("~/bundles/scripts")
@Styles.Render("~/Content/css")
In a typical ASP.NET MVC 5 configuration, bundling and minification are enabled for optimized output when debug="false" is configured in Web.config. The exact behavior also depends on the bundle configuration.
7. Interview Answer
Minification is the process of removing unnecessary characters from HTML, CSS, and JavaScript files without changing their functionality. It reduces file size and can improve download performance. It is commonly used alongside bundling and HTTP compression to optimize website performance.
| ASP.NET Interview Questions 31 to 40 :👈 | 👉:EF: ObjectContext and DbContext |