Core Interview Questions and Answers
Core Interview Questions and Answers
All rights reserved. No part of this book can be reproduced or stored in any retrieval system or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the Dot Net Tricks Innovation Pvt. Ltd.
The author of this book has tried their best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author or Dot
Net Tricks Innovation Pvt. Ltd. will not be liable for any damages, incidental or consequential caused directly or
indirectly by this book.
Further, readers should be aware that the websites or reference links listed in this book may have changed or
disappeared between when this book was written and when it is read.
All other trademarks referred to in this book are the property of their respective owners.
Release History
Initial Release 1.0 - 30th Nov 2018
Second Release 1.1 - 4th Jan 2019
Third Release 2.0 - 20th Dec 2019
Fourth Release 3.0 - 19th Mar 2021
1
Page
About Dot Net Tricks
Dot Net Tricks is founded by Shailendra Chauhan (Microsoft MVP), in Jan 2010. Dot Net Tricks came into existence
in the form of a blog post over various technologies including .NET, C#, SQL Server, ASP.NET, ASP.NET MVC,
JavaScript, Angular, Node.js and Visual Studio, etc.
The company which is currently registered by a name of Dot Net Tricks Innovation Pvt. Ltd. came into shape in
2015. Dot Net Tricks website has an average footfall on the tune of 300k+ per month. The site has become a
cornerstone when it comes to getting skilled-up on .NET technologies and we want to gain the same level of trust
in other technologies. This is what we are striving for.
We have a very large number of trainees who have received training from our platforms and immediately got
placement in some of the reputed firms testifying our claims of providing quality training. The website offers you
a variety of free study material in the form of articles.
.NET Development
Front-end Development
Cloud
DevOps
Programming Languages
Database - SQL and NoSQL
Mobile Development
ML/AI and many more...
Corporate Training
Dot Net Tricks has a pool of mentors who help the corporation enhance their employment skills by changing the
technology landscape. Dot Net Tricks offers customized training programs for new hires and experienced
employees through online and classroom mode. As a trusted and resourceful training partner, Dot Net Tricks helps
the corporation achieve success with its industry-leading instructional design and customer training initiatives.
Apart from these, we also provide on-demand boot camps and personalized project consultation.
Technical Recruiting
We provide a full technical staffing service, which suits our client's needs. Our specialized recruiters search
worldwide to find highly skilled professionals that will fit our client's needs. If you are looking for a job change, do
share your resume at [email protected]. Dot Net Tricks will help you to find your dream job in MNCs.
Join us today, learn to code, prepare yourself for interviews, and get hired!
3
Page
Dedication
I would like to say many thanks to my mother Mrs Saryuben Trivedi and my wife Mrs Poorvi for their support.
They deserve to have their name on the cover as much as I do for all their support made this possible. I would also
like to say thanks to all my family members Girish Kumar Trivedi (father), Rakesh and Tejas (brother) for their
continuous guidance and support to achieve my goals.
-Jignesh Trivedi
4
Page
Introduction
What Where Author Qualification to Write This Book
Jignesh Trivedi is awarded as MVP by Microsoft for his exceptional contribution in Microsoft technologies under
the category "Developer Technologies" for the year 2016, 2017, 2018 and 2019. He has more than 12 years of
experience on Microsoft technologies such as ASP.NET, MVC, ASP.NET Core, TypeScript, Blazor, SQL server etc.
and other technologies such as Angular and AngularJS, HTML, CSS, jQuery etc.
He is also a blogger and author of articles on various technologies. He is also a speaker and delivered talk on
various technologies like ASP.NET Core, Angular, MVC etc. in public events.
Our best wishes always with you for your learning and growth!
5
Page
About the Author
Jignesh Trivedi - An Author, Architect, and Microsoft MVP
Jignesh Trivedi is working as a software developer with a leading
organization and having more than 12 years of experience. He is very
passionate about the Microsoft Technologies. He is author, speaker and
MVP.
He loves building great products and POC (proof of concepts) using the
best available technologies. He loves to share his knowledge by
contributing to Developer community.
He always tries to keep updated himself about new technologies and learning new skills and shared with other
in simple manner. He hopes that this e-book helps you to crack interview of ASP.NET Core.
6
Page
How to Contact Us
Although the author of this book has tried to make this book as accurate as it possible but if there is something
that strikes you as odd, or you find an error in the book please drop a line via e-mail.
[email protected]
[email protected]
We are always happy to hear from our readers. Please provide your valuable feedback and comments!
You can follow us on YouTube, Facebook, Twitter, LinkedIn and Google Plus or subscribe to RSS feed.
7
Page
Table of Contents
ASP.NET Core Interview Questions & Answers ............................................................... 1
Release History ....................................................................................................................................................1
About Dot Net Tricks ...........................................................................................................................................2
Unlimited Live Training Membership .................................................................................................................2
Self-Paced Training Membership .......................................................................................................................2
Interview Q&A eBooks .......................................................................................................................................3
Corporate Training..............................................................................................................................................3
Technical Recruiting ...........................................................................................................................................3
Dedication ...........................................................................................................................................................4
Introduction ........................................................................................................................................................5
About the Author ................................................................................................................................................6
How to Contact Us...............................................................................................................................................7
Q31. Can we have mixed routing (conventional and attribute routing) into one app? .................................. 32
Page
Q2. How does model binding work in ASP.NET Core application? ................................................................ 49
Q3. What are the characteristics of a complex type for binding the value? ................................................. 49
Q4. Can we control the behaviour of Model binding using attribute? .......................................................... 50
Q5. Can we create a custom model binder? If yes how?............................................................................... 50
Q6. How can we use/register a custom model binder in ASP.NET Core?...................................................... 50
Q7. How can apply a custom model binder using ModelBinder attribute? .................................................. 50
Q8. How can we register a custom model binder globally? .......................................................................... 51
Q9. What is the use of BindProperty and BindProperties attribute? ............................................................ 51
Q10. What happened when “SupportsGet” property of BindProperty attribute is set to true? .................... 52
Q11. How can we do model validation with ASP.NET Core? ........................................................................... 52
Q12. How can we check our model is valid or not at the controller level? ..................................................... 52
Q13. What are the sources for model binding to get data from HTTP request? ............................................. 52
Q14. Which part of the MVC framework responsible to set IsValid property of ModelState class? .............. 52
Q15. Can we validate the model manually in Controller class? ....................................................................... 53
Q16. How can we do Client-side validation? ................................................................................................... 53
Q17. What are types that model binder can convert from source string? ...................................................... 53
Q18. What are built-in validation attributes provided with ASP.NET Core? ................................................... 53
Q19. How can we create a custom validation attribute? ................................................................................ 54
Q20. How can we disable client-side validation?............................................................................................. 54
Deployment ................................................................................................................... 86
Q1. What are the different techniques for hosting an ASP.NET Core application?....................................... 86
Q2. What is Kestrel? ....................................................................................................................................... 86
Q3. How to add Kestrel server in ASP.NET Core application? ....................................................................... 86
Q4. Can we bind the TCP socket with Kestrel server? ................................................................................... 87
Q5. What is HTTP.sys server? ......................................................................................................................... 87
Q6. What are the features are supported by HTTP.sys server?..................................................................... 87
Q7. How to host an application using HTTP.sys server? ................................................................................ 87
Q8. How to host ASP.NET Core application as a Windows service? .............................................................. 87
Q9. What is ASP.NET Core Module? .............................................................................................................. 88
Q10. What is in-process and out-of-process hosting model in ASP.NET Core? ............................................... 88
15
References ..................................................................................................................... 89
Page
1
Introducing ASP.NET Core
Q1. What is the ASP.NET Core?
Ans. ASP.NET Core is not an upgraded version of ASP.NET. ASP.NET Core is completely rewriting that work with
the .NET Core framework. It is much faster, configurable, modular, scalable, extensible and cross-platform
support. It can work with both .NET Core and .net framework via .NET standard framework. It is best suitable for
developing cloud-based such as web application, mobile application, IoT application.
Q4. Can ASP.NET Core application work with full .NET 4.x Framework?
16
Ans. Yes. ASP.NET Core application works with full .NET framework via the .NET standard library.
Page
Q5. Explain the advantages of ASP.NET Core over ASP.NET?
Ans. There are the following advantages of ASP.NET Core over ASP.NET:
Q9. Can we configure the service and request pipeline without Startup class?
Ans. Yes, it can be achieved by defining ConfigureServices and Configure convenience methods on the host
builder in the program class. If the multiple ConfigureServices method call exists, all methods are appended to
one another. The last Configure method call is used when multiple Configure method calls exist.
public class Program
17
{
public static void Main(string[] args)
Page
{
CreateHostBuilder(args).Build().Run();
}
Blazor: It is a new client framework for building interactive client-side web UI with .NET Core. You can
create rich UI using C# code instead of JavaScript and provides almost all feature that SPA provides.
New JSON serialization: The new JSON serialization is added under System.Text.Json namespace. It
provides higher performance than Newtonsoft.Json.
Two new Razor directives introduced: ASP.NET Core 3.0 introduced the following two new Razor directive.
o @attribute: It applied the given attribute to the view or class generated the page
o @implements: It is used to implements an interface for the generated class
ASP.NET Core 3.0 IdentityServer4 supports authentication and authorization for SPA and API
ASP.NET Core 3.0 template use .NET generic host (HostBuilder) instead of WebHostBuilder.
.NET Core 3.0 introduces the new Worker Service app template that provides a starting point for writing
long-running service
It introduced a shared framework that automatically referenced when using the Microsoft.NET.Sdk.Web
SDK in the project file
Introduced pipes on HttpContext: It is possible to read the request body and write the response body
using the System.IO.Pipelines API
Health Checks use endpoint routing with the Generic Host
18
Template updated
o Default web UI template update to removed cookie consent UI and remove references of CDN
(instead of new template use local files)
o Angular template update to support Angular 8
o RCL (Razor class library) update to supports Razor component by default and new templates are
added to supports pages and views
Kestrel configuration has been updated for the migration to the Generic Host
HTTP/2 protocol enable by default in Kestrel however for IIS and HTTP.sys, it is depending on the operating
system
Improved error reporting in IIS
Improvements in performance
o Reduced memory usage when using built-in DI container for scoped service
o Reduced memory usage for WebSocket connection
o Provides newly optimized and fully asynchronous JSON serializer
o Reduced memory usage and throughput improvements in form parsing and for HTTPS
connections
Following assemblies removed from the ASP.NET Core shared framework
o Newtonsoft.Json
o Entity Framework Core
services.AddResponseCompression(options =>
{
Page
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
}
ASP.NET Core provides improved tooling and runtime experiences for creating swagger documents. Further
information about swagger can be found here https://swagger.io/
21
Page
2
Middleware and Routing
Q1. How to add middleware to the application request pipeline?
Ans. Using IApplicationBuilder.Use, IApplicationBuilder.Map and IApplicationBuilder.Run methods, we can
add middleware delegate to the application request pipeline.
Q3. What is the use of "Map" extension while adding middleware to ASP.NET
Core pipeline?
Ans. It is used for branching the pipeline. It branches the ASP.NET Core pipeline based on request path
matching. If the request path starts with the given path, middleware on to that branch will execute.
{
app.MapWhen(context => context.Request.Query.ContainsKey("id"),
Middleware1);
}
All the middleware(s) are added to the ASP.NET Core pipeline in the order they have been added.
Q7. Explain the order of request processing pipeline for ASP.NET Core MVC
and Razor Pages apps
Ans. The following diagram explains the request/response processing pipeline for ASP.NET Core MVC and
Razor Pages apps.
23
Page
Q8. What is built-in middleware(s) available with ASP.NET Core?
Ans. Followings middleware ships with ASP.NET Core.
Middleware Description Method to invoke
(IServiceCollection/IApplicationBuilder)
Authentication Provide the authentication support AddDefaultIdentity or AddIdentity/
UseAuthentication
Authorization Provide the authorization support AddAuthorization or
AddAuthorizationCore or
AddAuthorizationPolicyEvaluator /
UseAuthorization
Cookie Policy Used to configure the cookie policy UseCookiePolicy
CORS Configure Cross-origin resource sharing AddCors /UseCors
Diagnostics Configures diagnostics UseDeveloperExceptionPage
Forwarded Headers Forwards proxied headers onto the UseForwaredHeaders
current request
Health Check Its check health for the ASP.NET Core AddHealthChecks / define endpoint for
app and its dependencies it using UseEndpoints
Header Propagation Propagates HTTP headers from the
incoming request to the outgoing HTTP
Client requests.
HTTP Method Override Allows an incoming POST request to UseHttpMethodOverride
override the method
HTTPS Redirection Redirect all HTTP request to HTTPS UseHttpsRedirection
HTTP Strict Transport It provides security enhancement (add UseHsts
Security (HSTS) special response header). It is available
with only ASP.NET Core 2.1 or later.
MVC Add MVC to request pipeline AddMvc
AddControllers
24
AddRazorPages
AddControllersWithViews
Page
/ UseMvc
OWIN Add Owin middleware for UseOwin
authentication
Response Caching Provide support to cache the response AddResponseCaching /
UseResponseCaching
Response Compression Enable compressing responses AddResponseCompression
/UseResponseCompression
Request Localization Provide support for localization AddLocalization/
UseRequestLocalization
Endpoint Routing Define route and constrain UseEndpoints
Session Add session middleware to request AddSession/UseSession
pipeline
Static Files Add support for accessing static files UseStaticFiles
and directory browsing
URL Rewriting Provide URL rewriting and redirect the UseRewriter
request
Web Sockets Enable the support for web socket UseWebSockets
Note: you can learn more about the middleware describe above from the following link.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0#built-in-
middleware
{
return builder.UseMiddleware<MyMiddleware>();
}
}
In the above example, the default route is added. It can match URL path such as "Employee/Details/10" and MVC
will extract the route values: controller as an employee, action as Details and id as 10.
The ASP.NET Core MVC can also add the above conventional route using the convenience method
UseMvcWithDefaultRoute.
app.UseMvcWithDefaultRoute();
Q15. What's happened MVC find two disambiguating actions through routing?
Ans. When MVC find two disambiguating actions, MVC chooses the best match or else throw an exception.
[Route("")]
[Route("Home")]
[Route("Home/Index")]
public IActionResult Index()
{
return View()
}
The above defined action method will be called for URL path "/","/Home", "/Home/Index".
When we define the route attribute on the controller, they are combined with the route defined on the action
method.
27
Page
Q17. Does ASP.NET Core support mix routing i.e. both conventional and
attribute routing together?
Ans. Yes, it supports mixed routing, but the action defined with attribute routes cannot reach through
conventional routes and vice-versa. If we mark the controller with attribute route, all actions under this controller
are now attribute routed.
app.UseMvc(routes =>
{
routes.MapAreaRoute("default_route", "AreaName", "AreaName/{controller}/{action}/{id?}");
});
For attribute route, MVC provides an "Area" attribute to define an area for the route.
Example
[Area("User")]
public class HomeController : Controller
{
….
….
}
[HttpGet("/employee")]
public IActionResult ListEmployee()
{
// ...
}
[HttpPost("/employee")]
public IActionResult CreateEmployee(...)
{
// ...
}
Q20. What are different HTTP verb templates supported by ASP.NET Core?
28
HttpGet
HttpPost
HttpPut
HttpDelete
HttpHead
HttpPatch
Syntax:
[Route(URLPath/{parameterName: constrain (type)})]
[Route("test/{age:int:min(8)}")]
public void TestMethod(int age) { }
After that custom route constraint registered with the app's ConstraintMap in the app's service container.
services.AddRouting(options =>
{
options.ConstraintMap.Add("consname", typeof(CustomRouteConstraint));
});
Q27. What are the different places where we can define routing in ASP.NET
Core?
Ans. Apps can configure routing using
30
Controllers
Razor pages
Page
SignalR
gRPC services
Endpoint enables middleware (example- Health checks)
Lambdas and delegates registered with routing
The endpoint routing does not use IRouter or Route based extensibility
It does not support Microsoft.AspNetCore.Mvc.WebApiCompatShim that provides a compatibility shim
to move ASP.NET 4.x Web API projects to ASP.NET Core
It has different behaviour for the casing of generated URIs with conventional routes
Consider following the default route
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
[Route("test")]
[Route("test1")]
public IActionResult Index()
31
{
}
Page
Q31. Can we have mixed routing (conventional and attribute routing) into one
app?
Ans. Yes, ASP.NET Core app can mix the use of both conventional and attribute routing into one app. Typical
use case of this to use the conventional route for the controller that serves HTML page and use attribute routing
for serving REST APIs.
}
}
Following are the steps to achieve dynamic routing based on the language selected
return values;
}
}
return null;
}
33
}
Page
app.UseEndpoints(endpoints =>
{
endpoints.MapDynamicControllerRoute<TranslationTransformerExample>
("{language}/{controller}/{action}");
}
RequireHost Example
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", context => context.Response.WriteAsync("Hi exmple!"))
.RequireHost("example.com");
}
}
[Host] Example
[Host("example.com")]
public class HomeController : Controller
{
public IActionResult Index()
{
return ControllerContext.MyDisplayRouteInfo();
}
[Host("example.com:8085")]
public IActionResult AccessPrivately()
{
34
return ControllerContext.MyDisplayRouteInfo();
}
Page
}
3
Session and Environment
Q1. How can we enable Session in ASP.NET Core?
Ans. The middleware for the session is provided by the package Microsoft.AspNetCore.Session. To use the
session in the ASP.NET Core application, we need to add this package to .csproj file and add the Session
middleware to the ASP.NET Core request pipeline.
Q4. Why Session is stored in the form of a byte array in ASP.NET Core?
Ans. The main reason to stored bytes array in session to make sure that values are serializable and can be
stored on the remote server.
Example
public class User
{
public string Name { get; set; }
public int Id { get; set; }
}
public class HomeController : Controller
{
public IActionResult TestMethod()
{
User u = new User() { Id = 1, Name = "Jignesh Trivedi" };
HttpContext.Session.SetString("MyData", JsonConvert.SerializeObject(u));
return View();
}
}
Ans. There are multiple ways to set the environment variable as given below:
Using Operating System: Operating System is also providing a way to set up an environment variable. The
environment variable is case-sensitive for macOS and Linux whereas it is case-insensitive for windows 10.
Using command prompt or Windows PowerShell command: using Set and $env command, we can set
environment variable
Using Visual Studio: We can set environment variable using VS by specified in our project's debug profiles.
The defined value in the launchSettings.json file
Q16. What are the various JSON files available in ASP.NET Core?
Ans. There are the following JSON files in ASP.NET Core:
global.json
launchsettings.json
appsettings.json
bundleconfig.json
bower.json
package.json
Q3. How to generate links for controller action under the area?
Ans. To identify the controller under view, we need to pass the area name in the route argument.
Example:
@Html.ActionLink("Test Area", "Index", "Home", new { area = "Account" })
Q4. How to generate links for controller action under the area using tag
helper?
Ans. The ASP.NET Core provides built-in tag helper to define action, controller and area. The "asp-controller"
tag helper uses to define controller, "asp-action" tag helper uses to define action method and "asp-area" tag
helper use to define area.
<a asp-area="Products" asp-controller="Item" asp-action="List">
Product Item List
</a>
[Area("Test")]
public class TestController : Controller
{
...
...
}
Q7. Can we change the folder name "Areas" to any other name?
Ans. Yes, we can change the folder name "Areas" to any other name. Using the area name, ASP.NET Core set
the default location where razor views are stored. If we change "Areas" to any other name, we must specify an
area view location path. The following code changes the default area folder from "Areas" to "TestAreas".
Example:
//HTML Helper
@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", placeholder = "Enter Your First
Name" })
//Equivalent HTML
<input placeholder="Enter Your First Name" class="form-control" id="FirstName" name="FirstName" value=""
type="text">
The tag helper looks the same as the HTML attribute or directive, so any who working with UI can easily
understand and edit razor view.
They are provided More robust, reliable and maintainable code
It executes the metadata such as DisplayName that using Data Annotation in the view model
Q10. What is the difference between HTML helper and Tag helper?
Ans. The functionality of the HTML helper and tag helper is nearly same but there are the following differences:
Syntax:
Page
@addTagHelper {name of the tag helper} {assembly name of the tag helper}
Example: _ViewImports.cshtml
@using TagHelper
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
In the above example, we have to use the wildcard character (*). It means that it adds the tag helpers define in
"Microsoft.AspNetCore.Mvc.TagHelpers" assembly to the Razor view.
Example:
Views/_ViewImports.cshtml
@tagHelperPrefix th:
index.cshtml
<div class="form-group">
<th:label asp-for="Firstname" class="col-md-6"></th:label>
</div>
Q14. Can we enable directory browsing through the code in ASP.NET Core?
Ans. Yes. We can enable directory browsing in ASP.NET Core using directory browsing middleware. We can
invoke the middleware using UseDirectoryBrowser method in configure method of the startup class.
Example:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
...
services.AddDirectoryBrowser();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
42
{
...
Page
...
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new
PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
RequestPath = "/ProjectImages"
});
...
...
}
}
Q16. What are built-in tag helpers provided with ASP.NET Core?
Ans. Following are Built-in ASP.NET Core Tag Helpers
Q17. How can we add a custom tag helper in ASP.NET Core MVC?
Ans. Following are the step to create a custom tag helper in ASP.NET Core.
Step 1: Define Tag helper class. Using the HtmlTargetElement attribute, we can provide a tag helper target. It
passes an attribute parameter that specifies the HTML element which contains an HTML attribute named.
[HtmlTargetElement("my-first-tag-helper")]
public class MyCustomTagHelper : TagHelper
{
public string Name { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "CustumTagHelper";
output.TagMode = TagMode.StartTagAndEndTag;
output.PreContent.SetHtmlContent(sb.ToString());
}
}
</my-first-tag-helper>
</div>
Output:
44
Page
5
Razor Pages and View
Component
Q1. What are the Razor Pages in ASP.NET Core?
Ans. This is a new feature introduced in ASP.NET Core 2.0. It follows a page-centric development model just
like ASP.NET web forms. It supports all the feature of ASP.NET Core.
Example:
@page
<h1> Hello, Book Reader!</h1>
<h2> This is Razor Pages </h2>
The Razor pages start with the @page directive. This directive handle request directly without passing through
the controller. The Razor pages may have a code-behind file, but it is not really a code-behind file. It is a class
inherited from PageModel class.
Q3. How can we enable Razor pages for ASP.NET Core app?
Ans. The Razor pages are enabled by adding middleware in ConfigureServices method of the Startup class.
public void ConfigureServices(IServiceCollection services)
{
...
...
services.AddRazorPages();
...
}
conventions to select the appropriate handler method to execute. It is On{Verb}[Async], where {Verb} is the HTTP
method (Get and post), and [Async] is optional.
Page
Q5. What are the handler methods available with Razor pages?
Ans. Following handler methods provided
OnPost and OnPostAsync run in response to POST requests
OnDelete and OnDeleteAsync run in response to DELETE requests
OnGet and OnGetAsync run in response to GET requests
OnHead run for HEAD requests when the handler is created
Example:
public class Test1Model : PageModel
{
[BindProperty]
public string Name { get; set; }
}
Example: Route with constrain (allow only int data for id)
@page "{id:int}"
Route parameter values store in RouteValueDictionary and we can access them using RouteData.Values property.
Example:
@RouteData.Values["id"]
<h2>@Model.MyData</h2>
<h2>@ViewData["MyData"]</h2>
Page
Q9. How can we apply filters in Razor pages?
Ans. There are two approaches:
1) Apply/register filter globally, so it applied to all the razor pages. By adding
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc(options =>
{
options.Filters.Add(new MyPageFilter());
});
}
Q11. What happened if view, partial view, or Razor Page found in both RCL
and web application?
Ans. ASP.NET Core always gives the first precedence to local files (web application) if view, partial view, or
Razor Page found in both RCL and web application.
optionally, we can decorate the class with the ViewComponent attribute. Here, the class name doesn't need to
be the same as the view component name. We can also set a view component by using the name property.
[ViewComponent(Name = "CustomerList1")]
public class CustomerList : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(int noOfEmployee)
{
...
...
return View();
}
}
Using Component.InvokeAsync method, view component can be invoked from view. This method has two
parameters: view component which needs to include and the parameter of the view component.
In the above example, route data (i.e. “2”) is bind with an id parameter.
Note that all the data source describes above-stored data as name-value pairs.
The model binder used reflection to bind properties value and recursion to traverse the properties of complex
types looks for a match. First, it will look for pattern parameter_name.property_name to bind values if it is not
found then it uses property name to bind the value.
Q3. What are the characteristics of a complex type for binding the value?
Ans. For binding to happen
49
The class must have public and default constructor (without parameter)
Properties that need to bind must be writable and public
Page
To create a custom model binder, the class must implement IModelBinder interface.
Example:
public class CustomModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}
Q7. How can apply a custom model binder using ModelBinder attribute?
Ans. There are two ways to apply a custom model binder using ModelBinder attribute.
1) Apply ModelBinder attribute to the model class
Example:
[ModelBinder(BinderType = typeof(CustomModelBinder))]
public class User
{
//...
50
}
Page
Example:
public class CustomModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(User))
return new CustomModelBinder();
return null;
}
}
Q12. How can we check our model is valid or not at the controller level?
Ans. The Model state represents validation errors on the submitted model. Model validation is done before to
action method invoked, so by inspecting ModelState.IsValid, we can validate our submitted model. If this property
set to false, your model is not valid.
Q13. What are the sources for model binding to get data from HTTP request?
Ans. Model binding gets the data from the following sources in HTTP request in the form of key-value pairs.
Form (using FromFormattribute)
Request body (using FromBody attribute)
Route Data (using FromRoute attribute)
Query string parameters (using FromQuery attribute)
Request header (using FromHeader attribute)
Uploaded files
Q14. Which part of the MVC framework responsible to set IsValid property of
ModelState class?
Ans. ModelBinder
52
Page
Q15. Can we validate the model manually in Controller class?
Ans. Base controller class ControllerBase has the method "TryValidateModel" that help us to validate the
model manually in the Controller class. This method returns true if the model is valid.
To perform the client-side validation, you must include jQuery and jQuery Unobtrusive Validation script file.
Q17. What are types that model binder can convert from source string?
Ans. The model binder can convert the following types from a source string
Boolean
Byte, SByte
Char
DateTime, DateTimeOffset, TimeSpan
Enum
Guid
Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal
Uri
Version
Q18. What are built-in validation attributes provided with ASP.NET Core?
Ans. Following are Built-in ASP.NET Core validation attributes
54
Page
7
Globalization and Localization
Q1. What is Internationalization in ASP.NET Core?
Ans. It involves Globalization and Localization. Globalization supports multiple cultures hence it used to create
multilingual websites with ASP.NET Core. Localization is a process of translating user interface according to specific
culture i.e., the application will display data based on the selected language.
Alternatively, we can put the resource file under a similar folder as the naming provided i.e. under folder
Resources/Controllers/HomeController.en-US.resx
Example:
@using Microsoft.AspNetCore.Mvc.Localization
Also, we need to register AddViewLocalization service in the ConfigureServices method of the startup class.
Page
There is no option for a globally shared resource file, but it can be achieved by using IHtmlLocalizer service.
Example:
public class MyController: Controller
{
private readonly IStringLocalizer<MyController> _localizer;
[HttpGet]
public string Get()
{
return _localizer["Title"];
}
}
Example
public class ModelClass
{
[Required(ErrorMessage = "RequiredName")]
public string Name { get; set; }
}
56
Page
Q6. How does the culture fallback mechanism work in ASP.NET Core?
Ans. The ASP.NET Core provides a strong culture fallback mechanism. It is starting from the requested culture,
if not found, look for parent culture. If parent culture is not found, it retrieves the value from the default resource
file. For example, if an application looking for fr-FR culture file. If it is not found, it looks for fr culture file and if
the resource not found in the parent, it looks in the default culture file.
Q7. What happens when resource not found in a culture resource file?
Ans. If resource not found in the culture resource file, the resource manager will find resource value from the
default resource file.
Q8. How can we return the resource key when the resource not found in the
culture file?
Ans. If we want to return the resource key when a resource not found from a culture resource file, we must
not have a default resource file.
Q9. Can we add Content-Language header With ASP.NET Core? If yes, how?
Ans. ASP.NET Core 3.0 allows you to add Content-Language header by setting the property
ApplyCurrentCultureToResponseHeaders of RequestLocalizationOptions.
app.UseRequestLocalization(new RequestLocalizationOptions
{
ApplyCurrentCultureToResponseHeaders = true
});
Q11. Is there any other way to set application culture other than Accept-
Language header approach?
Ans. ASP.NET Core has QueryStringRequestCultureProvider that set application culture from query string but
for same we have to pass query string parameters “culture” and “ui-culture”.
http://localhost:5000/?culture=fr-FR&ui-culture=fr-FR
57
Page
8
Exception Handling and
Logging
Q1. What is the "Developer Exception Page" in ASP.NET Core?
Ans. It is a feature that shows detailed information about the exception. This can be enabled using the
Developer Exception Page middleware. This middleware defined in Microsoft.AspNetCore.Diagnostics assembly.
To add this middleware to the request pipeline, we need to call IApplicationBuilder.UseDeveloperExceptionPage
method in Configure method of startup class.
Example
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
...
}
...
...
}
}
else
Page
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
...
...
}
Note that whatever route you mention here must available in the application.
Q3. Can we define custom exception without using defining error page?
Ans. Yes, we can define the custom exception handler page inline using lambda exception to
UseExceptionHandler. It allows accessing the error before returning the response.
In the following example, the error status code and the custom error message has been written to the response
object before returning the response.
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("</body></html>\r\n");
await context.Response.WriteAsync(new string(' ', 512)); // IE padding
});
});
Q7. What are the possible values for Log level enum for the Logging
framework?
Ans. Log level has the following possible values
Trace (0)
Debug (1)
Information (2)
Warning (3)
Error (4)
Critical (5)
None (6)
60
Page
Q8. How many built-in extension methods provided by the logging
framework of ASP.NET Core?
Ans. There are many built-in extension methods provided by the logging framework of ASP.NET Core.
Followings are the methods:
LogCritical: Format and write a critical log message
LogDebug: Format and write a debug log message
LogError: Format and write an error log message
LogInformation: Format and write an information log message
LogTrace: Format and write a trace log message
LogWarning: Format and write a warning log message
Log: Format and write a log message specifying the log level. This is a base method and the methods
describe above are called this method internally with different log level
Q10. How to set default minimum log level for Logging Framework?
Ans. Using LoggingBuilderExtensions.SetMinimumLevel method, we can set a minimum log level and is
effective only if no rules are defined either by code or configuration. This method calls from the main method of
program class.
In the above example, the minimum log level is set to warn so, the Logging framework ignores the log message
that below mentioned warning level.
Q11. How to define filter rule for the Logging framework in ASP.NET Core?
Ans. We can specify the logging filter rules either by using a Configuration file or using C# code. We can specify
the logging filter rules in any configuration file such as appsettings.json. The first step is to add a JSON
configuration file and add a configuration section to the logging framework. In the following code example, I have
followed the steps mention here.
Example:
61
Appsettings.json
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Information"
}
},
"Console": {
"LogLevel": {
"Microsoft.AspNetCore.Mvc.Razor": "Error",
"Microsoft.AspNetCore.Mvc.Razor.Razor": "Error",
"Default": "Information"
}
},
"LogLevel": {
"Default": "Debug"
}
}
}
The same thing can be achieved using the C# code using the AddFilter method.
logging.AddFilter<Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider>("System",
Page
LogLevel.Information);
logging.AddFilter<Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider>("Microsoft.AspNe
tCore.Mvc.Razor", LogLevel.Error);
logging.AddFilter<Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider>("Microsoft.AspNe
tCore.Mvc.Razor.Razor", LogLevel.Error);
logging.AddFilter<Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider>("System",
LogLevel.Information);
...
...
})
.UseStartup<Startup>();
In controller Action
public IActionResult TestMethod()
{
using (_logger.BeginScope("Log Scope Start"))
{
_logger.LogInformation("Example Scope");
_logger.LogWarning("My Scope");
}
return View();
}
Q13. What are third party logging frameworks supported by ASP.NET Core?
Ans. Following are third party logging framework that supported by ASP.NET Core and all are available in
GitHub repository.
elmah.io
Gelf
JSNLog
KissLog.net
Loggr
NLog
63
Sentry
Serilog
Page
Stackdriver
Log4net
64
Page
9
Dependency Injection
Q1. How does dependency injection work in ASP.NET Core?
Ans. There is built-in support for dependency injection in ASP.NET Core. This support is not limited to
middleware but also support Controllers, Views and Models. The services that are added to the service container
are available as dependency service.
Q3. How can we inject the service dependency into the controller?
Ans. There are three easy steps to add custom service as a dependency on the controller.
Step 1: Create the service
public interface IHelloWorldService
{
string SaysHello();
}
Step 2: Add this service to “Service container” (service can either added by singleton, transient or scoped)
public void ConfigureServices(IServiceCollection services)
{
….
…
services.AddTransient<IHelloWorldService, HelloWorldService>();
…
…
}
65
Page
Q4. Can we inject the dependency to the individual action method of the
controller?
Ans. Yes. Using the “FromServices" attribute, we can inject the dependency to the individual action method of
the controller. This attribute tells the ASP.NET Core framework that parameter should be retrieved from the
service container.
Example:
public IActionResult Index([FromServices] IHelloWorldService helloWorldService)
{
ViewData["MyText"] = helloWorldService.SaysHello() + "Jignesh!";
return View();
}
Q6. How to specify a service life for register service that added as a
dependency?
Ans. ASP.NET Core allows us to specify the lifetime for registered services. The service instance gets disposed
of automatically based on a specified lifetime. So, we do not care about cleaning these dependencies, it will take
care by the ASP.NET Core framework. There are three types of lifetimes.
Singleton
ASP.NET Core will create and share a single instance of the service through the application life. The service can be
added as a singleton using the AddSingleton method of IServiceCollection. ASP.NET Core creates a service instance
66
at the time of registration and subsequence request use this service instance. Here, we do not require to
Page
implement Singleton design pattern and single instance maintained by the ASP.NET Core itself.
Example:
services.AddSingleton<IHelloWorldService, HelloWorldService>();
Transient
ASP.NET Core will create and share an instance of the service every time to the application when we ask for it.
The service can be added as Transient using AddTransient method of IServiceCollection. This lifetime can be used
in stateless service. It is a way to add lightweight service.
Example:
services.AddTransient<IHelloWorldService, HelloWorldService>();
Scoped
ASP.NET Core will create and share an instance of the service per request to the application. It means that a single
instance of service available per request. It will create a new instance in the new request. The service can be added
as scoped using an AddScoped method of IServiceCollection. We need to take care of while, service registered via
Scoped in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject dependency via
the constructor, it behaves like a singleton object.
services.AddScoped<IHelloWorldService, HelloWorldService>();
Q7. How can we inject the service dependency into the View?
Ans. There are three easy steps to add custom service as a dependency into the View.
Step 1: Create the service
public interface IHelloWorldService
{
string SaysHello();
}
Step 2: Add this service to the Service container (service can either added by singleton, transient or scoped)
public void ConfigureServices(IServiceCollection services)
{
….
…
services.AddTransient<IHelloWorldService, HelloWorldService>();
…
…
}
67
Step 3: Inject the dependency to view using the @inject directive. Here we need to pass the service type and
instance name that is used to access the service method.
Page
<h4>DI To View</h4>
<h5>
@helloWorldService.SaysHello() Reader!!!
</h5>
Q8. What point you will be taken care of while creating a service for DI?
Ans. Following are the best practices to create service for DI
Do not create static methods
Services able to obtain their own dependencies
Avoid creating stateful service
Avoid direct instantiation of dependent classes within services
Make service classes small and well-factored, so can be easily tested
68
Page
10
Security and Filters
Q1. What is the use of a filter in the ASP.NET Core application?
Ans. Filters allowed us to execute custom code after and before executing the action method. They are invoked
at various stage of the application life-cycle. There are many built-in filters are available with ASP.NET Core
application such as Authorize, HttpGet, HttpPost etc.
69
Page
Q4. How can we create a custom filter in ASP.NET Core?
Ans. To implement a synchronous filter, the class must implement IActionFilter interface. This interface has
two abstract methods: OnActionExecuting and OnActionExecuted. The method OnActionExecuting is called
before the action executing and OnActionExecuted method is called after an action executed.
using Microsoft.AspNetCore.Mvc.Filters;
namespace CustomFilters
{
public class MyActionFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
}
}
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CustomFilters
{
public class AsyncActionFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context,
ActionExecutionDelegate next)
{
//To do : Code that execute before the action executes
await next(); //Action Execution
//To do : Code that execute after the action executes
}
}
}
Q10. Can we override the default order of execution of filter in ASP.NET Core?
Ans. Yes, we can override the default order of execution of filter by using implement IOrderedFilter interface.
This interface has a property called "Order" that is used to define the order. The filter with a lower Order property
value will execute first. ASP.NET Core application sorted the filter by order first and then the scope of the filter.
Example:
71
using Microsoft.AspNetCore.Mvc.Filters;
namespace WebApplication1
Page
{
public class MyActionFilter : IActionFilter, IOrderedFilter
{
public int Order { get; set; }
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
}
}
Q11. Does the built-in filter also implement the interface IOrderFilter?
Ans. Yes, the built-in filter implements the IOrderFilter interface and the default value for the order property
is set to 0 (zero).
Q14. Can you apply a filter attribute having constructor dependency to the
controller or action?
Ans. The filter that applied directly to the controller or its action cannot have constructor dependency. This is
a limitation of the filter attribute. But there is a way to overcome this limitation. There is a built-in attribute
available, with the help of them we can apply such filter to controller or action method. Following are the built-in
attribute.
ServiceFilterAttribute
TypeFilterAttribute
Example:
public class CustomExceptionFilterAttribute : Attribute, IExceptionFilter
{
public void OnException(ExceptionContext context)
{
var exception = context.Exception;
//Do something with exception
Authorization is a process of checking user rights i.e., determines whether the user can do this. ASP.NET Core has
built-in support of identity providers however it can also support 3rd party identity service such as Twitter,
Facebook, Microsoft account etc.
Q24. How can we configure a built-in identity service for ASP.NET Core
application?
Ans. By calling AddDefaultIdentity or AddIdentity in ConfigureService method of the startup class, we can add
a built-in identity service to the request pipeline. This service can be enabled by calling UseAuthentication in
Configure method of the startup class.
By decorating a controller or action method with Authorize attribute that you apply authorization.
Example:
public void ConfigureServices(IServiceCollection services)
{
// Overide the configuration
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = true;
});
}
Using this identity option, we can override the following default configuration
PasswordOptions (Password Policy)
LockoutOptions(User's lockout)
UserOptions (User validation settings)
SignInOptions(Sign in settings)
ConfigureApplicationCookie(Cookie settings for Application)
75
Page
>dotnet new MVC --auth windows
2) It can be configured manually using Visual Studio project properties. Open Visual Studio project properties >>
go to Debug tab and checked the "Enable Windows Authentication" checkbox.
Q28. How can we enforce HTTPS for all requests in ASP.NET Core?
Ans. ASP.NET Core provides middleware that redirects HTTP requests to HTTPS. We can inject the middleware
76
into the request pipeline using the UseHttpsRedirection method of the IApplicationBuilder object.
Page
Q29. Is there any alternative approach for enforcing Https other than injecting
middleware?
Ans. Yes, HTTPS Redirection middleware is to use URL rewriting middleware (AddRedirectToHttps), we can also
use URL rewriting middleware and set additional rule for redirection.
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/test", async context => context.Response.WriteAsync("test"))
.RequireCors("policy name");
});
Enable CORS using middleware
ASP.NET Core provides CORS middleware. If we use CORS middleware, CORS policies to all the apps endpoints.
ASP.NET Core provides tag helper "asp-anti forgery" that enable /disable anti-forgery for the page. If this tag
helper value is set to "true", it means that it enables the anti-forgery for this page.
using the ValidateAntiForgeryToken attribute, we can check whether the token is valid or not at the server side
(controller/action method).
[ValidateAntiForgeryToken]
public class AccountController : Controller
{
//...
//...
}
[Authorize(Roles = "Admin")]
public class HomeController : Controller
{
{
options.AddPolicy("UserPolicy", policy =>
Page
policy.UserRequireCustomClaim(ClaimTypes.Email);
policy.UserRequireCustomClaim(ClaimTypes.DateOfBirth);
});
}
[Authorize(Policy = "UserPolicy")]
public class HomeController : Controller
{
79
Page
11
Unit Testing
Q1. What Unit Testing frameworks can be used with ASP.NET Core?
Ans. Mainly there are three unit testing frameworks people use with ASP.NET Core.
MSTest
xUnit
NUnit
Q2. How can we write a unit test with the MSTest framework?
Ans. To write a unit test using the MSTest framework, create a class and this denotes with TestClass attribute.
Create test method under this class as many as you want but denote the methods with the TestMethod attribute.
Example
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
}
}
Q3. Can we create an MSTest project using command line interface (CLI)?
Ans. Yes, using the following command we can create a MSTest project with CLI.
dotnet new MSTest
{
int expected = 1;
Page
int actual = 1;
Assert.AreEqual(expected, actual);
}
We can also run the test from test explore or from individual test method from the code reference.
[DataTestMethod]
[DataRow(1,"Test")]
[DataRow(2, "Test 1")]
public void TestMethod2(int Id, string name)
{
//do something
}
81
Page
Q7. How can we write a unit test with xUnit framework?
Ans. The xUnit is an open-source and community-focused unit testing framework. To write a unit test using the
xUnit framework, create a class and create a test method under this class as many as you want but denote the
methods with the Fact attribute.
[Fact]
public void Test1()
{
//do something.
}
Q14. How can we create a test for the controller that has service dependency?
Ans. We can get the service instance object using the GetService method of the service provider class. To test
the controller having such a dependency, we can create an instance of a service provider class and get the required
service instance.
83
In the following example, Controller having a dependency on ILogger service. So, I have created an object of the
Page
service provider and using the service provider class object of such services can be created.
public void TestMethod1()
{
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
Example:
public void Test1()
{
var mock = new Mock<IDataRepository>();
mock.Setup(p => p.GetNameUsingId(100)).Returns("This is test");
HomeController home = new HomeController(mock.Object);
string result = home.GetNameUsingId(100);
//Verify the result
}
Unit tests use to test isolated app component such as individual class methods. Integration tests use to
test two or more app components work together to produce an expected result
Unit tests use fabricated components (Mock object) whereas Integration tests use infrastructure
components such as actual database and file system
Integration tests may take a longer time to execute as they interact with actual infrastructure
components
84
It is recommended to use a unit test instead of integration tests whereas possible and it is not
recommended to use integration tests to check every possible permutation of data
Page
Q18. What is the load test and stress test?
Ans. Load testing and stress testing are used to test web app performance and scalability. Load testing test
web app can handle a specified number of user load for a certain scenario. The stress testing test web app
scalability and stability when the app running under extreme conditions for a long period.
Q19. What are the tools used for web performance testing?
Ans. Following are the tools that can be used for web performance testing
85
Page
12
Deployment
Q1. What are the different techniques for hosting an ASP.NET Core
application?
Ans. ASP.NET Core can be hosted in multiple ways such as
In Program class (entry point of the project), the template code calls WebHost.CreateDefaultBuilder method that
calls UseKestrel method to use Kestrel server.
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
Page
.UseKestrel(options =>
{
//set properties of Kestrel server
});
}
We can also handle service start / stop event for windows service.
88
Page
References
89
Page