Basic to advance ASP.Net Framework
Basic to advance ASP.Net Framework
1. What is 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.
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.
o GET: Sends data to the server via the URL (query string). It is
less secure as data is visible in the URL.
Secure cookies
Here are answers with examples for each of the questions listed:
Example:
Example:
HttpContext.Current.Session["User"] = "JohnDoe";
Example:
<uc:MyControl runat="server" id="UserControl1" />
Example:
POST (Form):
Example:
try
Response.Redirect("ErrorPage.aspx");
}
7. What are the types of authentication in ASP.NET?
Example:
Response.Cookies["username"].Value = "JohnDoe";
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>
Example:
Response.Write("Hello, world!");
12. What is the role of Session_Start and Session_End in the
Global.asax file?
Example:
Example:
Session["User"] = "JohnDoe";
Example:
if (User.Identity.IsAuthenticated)
// User is authenticated
Example:
Example:
Response.Redirect("AnotherPage.aspx");
Enabled: Controls whether the user can interact with the control.
Example:
Button1.Visible = false;
Button1.Enabled = false;
Example:
Example:
Example:
Example:
writer.Write("<button>Custom Button</button>");
Example:
A Literal control displays static text on the page without any HTML
tags.
Example:
form1.Controls.Add(literal);
27. What are the differences between HTML controls and Web
controls in ASP.NET?
Example:
28. What are the differences between Inline and CodeBehind modes
of ASP.NET Web Forms?
Example:
The App_Data folder is used to store database files, XML files, and
other data files that should not be accessible to the client.
You create a form using ASP.NET controls like TextBox, Button, etc.,
and set the runat="server" attribute.
Example:
</form>
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?
Example:
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
33. What are Custom Controls and User Controls in ASP.NET? How
are they different?
Example:
Types of Caching:
Example:
HttpContext.Current.Cache["MyData"] = myData;
Example:
[OutputCache(Duration = 60)]
Example:
GridView1.DataSource = myDataSource;
GridView1.DataBind();
Example:
Example:
[ActionFilter]
41. What is ASP.NET MVC and how does it differ from Web Forms?
Routing maps URLs to actions in the controller. The routes are defined
in RouteConfig.cs.
Example:
Example:
ViewData: Stores data for the current request and is available in the
view.
TempData: Stores data that survives only until the next request.
Example:
ViewData["Message"] = "Hello";
ViewBag.Message = "Hello";
TempData["Message"] = "Hello";
Example:
Example:
@Html.Partial("PartialViewName")
Example:
_myService = myService;
48. What are the differences between ASP.NET Core and ASP.NET
MVC?
Example:
app.UseAuthentication();
app.UseAuthorization();
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:
<button type="submit">Submit</button>
</form>
Example:
services.AddControllersWithViews();
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Example:
[Authorize(Roles = "Admin")]
53. What is JWT (JSON Web Token) and how does it work in ASP.NET
Core?
Example:
};
issuer: Configuration["Jwt:Issuer"],
audience: Configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
ASP.NET Core Identity is a set of APIs and tools for managing user
authentication, registration, and roles in an ASP.NET Core application.
Example:
[Authorize(Roles = "Admin")]
Example:
}
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.
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()
options.ClientId = Configuration["GitHub:ClientId"];
options.ClientSecret = Configuration["GitHub:ClientSecret"];
});
60. What are ASP.NET Core Razor Pages? How do they differ from
MVC?
[Route("home/index")]
Example:
base.OnActionExecuting(context);
Example:
return View(data);
65. What is Task Parallel Library (TPL) and how is it used in ASP.NET
applications?
Example:
Example:
services.AddApiVersioning(options =>
options.ReportApiVersions = true;
});
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
Example:
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
return Ok(data);
Example:
[Required]
[StringLength(50)]
[EmailAddress]
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.
Example:
if (ModelState.IsValid)
else
return View(model);
Example:
_httpContextAccessor = httpContextAccessor;
}
return _httpContextAccessor.HttpContext.Request.Path.ToString();
Example:
[Route("api/[controller]")]
[HttpGet]
// Retrieve products
return Ok(products);
[HttpGet("{id}")]
// Retrieve product by id
return Ok(product);
}
Example:
Example:
_cache = cache;
return Ok(myData);
_myService = myService;
return View(data);
Example:
// appsettings.json
"MySettings": {
"ConnectionString": "Server=myserver;Database=mydb;"
}
public class MyService
_configuration = configuration;
return _configuration["MySettings:ConnectionString"];
Example:
_next = next;
}
public async Task InvokeAsync(HttpContext context)
await _next(context);
app.UseMiddleware<CustomMiddleware>();
while (!stoppingToken.IsCancellationRequested)
{
services.AddHostedService<MyBackgroundService>();
Example:
bindingContext.Result = ModelBindingResult.Success(date);
else
{
bindingContext.ModelState.AddModelError("date", "Invalid date
format");
return Task.CompletedTask;
services.AddControllers(options =>
options.ModelBinderProviders.Insert(0, new
CustomModelBinderProvider());
});
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:
HttpContext.Session.SetString("Username", "JohnDoe");
return View();
}
public IActionResult GetUsername()
return Content(username);
services.AddDistributedMemoryCache();
services.AddSession(options =>
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
app.UseSession();
{
services.AddStackExchangeRedisCache(options =>
options.Configuration = "localhost:6379";
options.InstanceName = "SampleApp:";
});
_cache = cache;
if (string.IsNullOrEmpty(cachedData))
return Ok(cachedData);
}
85. How do you enable HTTPS in an ASP.NET Core application?
Example:
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
endpoints.MapControllers();
});
services.AddHttpsRedirection(options =>
options.HttpsPort = 5001;
});
Example:
public void Configure(IApplicationBuilder app)
app.UseWebSockets();
if (context.WebSockets.IsWebSocketRequest)
await HandleWebSocketAsync(webSocket);
else
await next();
});
while (!result.CloseStatus.HasValue)
await webSocket.CloseAsync(result.CloseStatus.Value,
result.CloseStatusDescription, CancellationToken.None);
4. The app uses the access token to make API calls on behalf of the user.
services.AddAuthentication(options =>
options.DefaultScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme =
GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
options.ClientId = Configuration["Google:ClientId"];
options.ClientSecret = Configuration["Google:ClientSecret"];
});
Example:
[ApiController]
[Route("api/[controller]")]
[HttpGet]
return Ok(products);
[HttpPost]
}
[HttpGet("{id}")]
// Retrieve a product by ID
return Ok(product);
89. How do you log exceptions and events in ASP.NET Core using
ILogger?
Example:
_logger = logger;
try
return View();
Example:
if (product == null)
return NotFound();
return Ok(product);
Here are the answers for the remaining questions from your list:
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:
5. {
6. services.AddSwaggerGen();
7. services.AddControllers();
8. }
11. {
12. app.UseSwagger();
14. {
16. });
17. }
5. using Serilog;
6.
8. {
10. {
12. .WriteTo.Console()
13. .CreateLogger();
14.
15. CreateHostBuilder(args).Build().Run();
16. }
17.
19. Host.CreateDefaultBuilder(args)
20. .UseSerilog() // Use Serilog for logging
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 {
o {
o }
o {
o }
o }
o {
o }
o {
o }
o }
o {
o {
o // Handle exception
o context.ExceptionHandled = true;
o }
o }
Example:
98. What is the difference between Web API and gRPC in ASP.NET
Core?
o {
o services.Configure<FormOptions>(options =>
o {
o });
o }
o [HttpPost]
o {
o if (file.Length > 0)
o {
o {
o await file.CopyToAsync(stream);
o }
o }
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:
5. {
6. services.AddHealthChecks();
7. }
8.
10. {
11. app.UseHealthChecks("/health");
12. }