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

ASP.NET Core Interview Questions And Answers

The document is a comprehensive guide on ASP.NET Core, featuring interview questions and answers designed to help developers enhance their understanding and prepare for job interviews. It covers various topics such as middleware, routing, session management, and security, along with training solutions offered by Dot Net Tricks. The author, Jignesh Trivedi, is an experienced Microsoft MVP who aims to share knowledge and assist others in mastering ASP.NET Core.

Uploaded by

mvljprasuna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

ASP.NET Core Interview Questions And Answers

The document is a comprehensive guide on ASP.NET Core, featuring interview questions and answers designed to help developers enhance their understanding and prepare for job interviews. It covers various topics such as middleware, routing, session management, and security, along with training solutions offered by Dot Net Tricks. The author, Jignesh Trivedi, is an experienced Microsoft MVP who aims to share knowledge and assist others in mastering ASP.NET Core.

Uploaded by

mvljprasuna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

ASP.

NET Core Interview Questions & 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

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 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 the 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 form of articles.

Dot Net Tricks Training Solutions


Dot Net Tricks provide you training in traditional as well as new age technologies, via various formats.

Master Courses (Instructor-led)

For a beginner who needs regular guidance, we have a fully packed Master Courses. They are almost equal to
semester courses taught in engineering colleges when it comes to length, breadth of content delivery, the only
difference instead of 5-6 months, they take approx. 16-weekend classes (2 months).

The detail about Master courses can be found here: https://www.dotnettricks.com/instructor-led-courses

Hands-On Learning (Learn to code)

Hands-On Learning courses give you the confidence to code and equally helpful to work in real-life scenarios. This
course is composed of hands-on exercise using IDE or cloud labs so that you can practice each and everything by
yourself. You can learn to code at your own pace, time and place.

The detail about Hands-On Learning courses can be found here: https://www.scholarhat.com

Skill Bootcamps (Instructor-led)

Professionals who don’t have two months’ time and want to get skilled up in least possible time due to some new
project that their company has to take in very near future, we have designed Skill Bootcamps Concept, where you
will get trained on consecutive days in a fast-paced manner, where our full focus is going to be on hands-on
delivery of technological exercises.
2

The detail about Skill Bootcamps can be found here: https://www.dotnettricks.com/skill-bootcamp


Page
Self-paced Courses

Self-paced courses give you the liberty to study at your own pace, time and place. We understand everyone has
their own comfort zone, some of you can afford to dedicate 2 hours a day, some of you not. Keeping this thing in
mind, we created these self-paced courses. While creating these courses we have ensured that quality of courses
doesn’t get compromise at any parameter, and they also will be able to produce the same results as our other
course formats, given the fact you will be able to put your own honest effort.

The detail about Self-paced courses can be found here: https://www.dotnettricks.com/self-paced-courses

Corporate Training (Online and Classroom)

Dot Net Tricks having a pool of mentors who help the corporate to enhance their employment skills as per
changing 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 corporate to achieve success with its industry-leading instructional design and customer training initiatives.

The detail about Corporate Training can be found here: https://www.dotnettricks.com/corporate-training

Learning Platform

We have a very robust technology platform to answer the needs of all our trainees, no matter which program they
enrolled in. We have a very self-intuitive Learning Management System (LMS), which help you in remain focused
and keeping an eye over your progress.

We offer two Learning Platforms as given below:

1. Dot Net Tricks: https://www.dotnettricks.com


2. Scholar Hat: https://www.scholarhat.com

Apart from these, we also provide on-demand Skill bootcamps and personalized project consultation.

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 and 2018. He has more than 11 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 the public events.

What This Book Is


ASP.NET Core is an open source, cross-platform framework for building web applications using C# and .NET. This
book will teach you ASP.NET Core concepts from scratch to advance with the help of Interview Questions &
Answers. Here, you will about the routing, tag helpers, middleware, session, dependency injection,
authentication, authorization, unit testing and deployment.

What You’ll Learn


This book is for .NET developers who are looking for a change or want to make a bright future in ASP.NET Core.
This book covers the interview questions on the following topics:

• ASP.NET Core features details.


• How to configure middleware and routing.
• How to enable session and configure your application environment.
• A JS framework like a way to write server-side code to create and render the HTML using Tag Helper.
• How to reuse your code using Partial views and view component.
• Different ways to apply validations and binding data to server-side action methods.
• How to implement localization and globalization.
• Handle exceptions and logging errors.
• Dependency Injection implementation.
• Ways to secure your application and using filters.
• Using Unit testing frameworks and running tests.
• Various Deployment options

Share to Help Others


Hope you will enjoy this book and find it valuable for yourself. The author is truly delighted about this if you will
share this book among others because he wants it to reach as many techy people as possible.
5
Page

Our best wishes always with you for your learning and growth!
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 11 years of experience. He is very
passionate about the Microsoft Technologies. He is author, speaker and
MVP.

He has experience to develop enterprise application using Microsoft


technologies such ASP.net Core, C#, SQL server, etc. and other
technologies such as Angular, node.js, etc.

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. This is the first edition of this book but
not last. Please provide your feedback that help us to improve this book quality.

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
strikes you as odd, or you find an error in the book please drop a line via e-mail.

The e-mail addresses are listed as follows:

[email protected]
[email protected]

We 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
Dot Net Tricks Training Solutions .........................................................................................................................2
Dedication ...........................................................................................................................................................4
Introduction ........................................................................................................................................................5
About the Author ................................................................................................................................................6
How to Contact Us...............................................................................................................................................7

Introducing ASP.NET Core .............................................................................................. 14


Q1. What is the ASP.NET Core?...................................................................................................................... 14
Q2. What are the features provided by ASP.NET Core? ................................................................................ 14
Q3. What is Metapackages?........................................................................................................................... 14
Q4. Can ASP.NET Core application work with full .NET 4.x Framework?....................................................... 14
Q5. What are advantages of ASP.NET Core over ASP.NET? ........................................................................... 15
Q6. What is the startup class in ASP.NET core? ............................................................................................. 15
Q7. What is the use of ConfigureServices method of startup class? ............................................................. 15
Q8. What is the use of Configure method of startup class? .......................................................................... 15

Middleware and Routing ............................................................................................... 16


Q1. How to add middleware to the application request pipeline? ............................................................... 16
Q2. What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run()? .................. 16
Q3. What is the use of "Map" extension while adding middleware to ASP.NET Core pipeline?................... 16
Q4. What is the use of "MapWhen" extension while adding middleware to ASP.NET Core pipeline? ......... 16
Q5. What is middleware? ............................................................................................................................... 17
Q6. How can we configure the pipeline for middleware? ............................................................................. 17
Q7. What is built-in middleware(s) with ASP.NET Core? ............................................................................... 17
Q8. Can we write our own middleware? ....................................................................................................... 18
Q9. What is routing in ASP.NET Core? ........................................................................................................... 19
Q10. How can we configure conventional routing?......................................................................................... 19
8

Q11. What's happened MVC find two disambiguating actions through routing? ........................................... 20
Page

Q12. What is Attribute routing? ...................................................................................................................... 20


Q13. Does ASP.NET Core support mix routing i.e. both conventional and attribute routing together? ......... 20
Q14. How can we define a route for areas? .................................................................................................... 20

Session and Environment Settings ................................................................................. 21


Q1. How to enable Session in ASP.NET Core?................................................................................................ 21
Q2. How many types of session state is available in ASP.NET Core?............................................................. 21
Q3. How to access the session in ASP.NET Core application? ....................................................................... 21
Q4. Why Session is stored in form of byte array in ASP.NET Core? ............................................................... 22
Q5. Is there any sequence to call UseSession() method in Configure method? ............................................ 22
Q6. Can we store the Complex data into the session? .................................................................................. 22
Q7. How to set an environment variable? ..................................................................................................... 23
Q8. Key for environment variable is case-sensitive? ..................................................................................... 23
Q9. How determine the value of an environment variable programmatically? ............................................ 23
Q10. What are the various JSON files available in ASP.NET Core? .................................................................. 23
Q11. What is the use of “launchsettings.json” file? ........................................................................................ 23
Q12. What is the use of "appsettings.json" file? ............................................................................................. 23
Q13. What is the use of "bower.json" file? ...................................................................................................... 23

Areas and Tag Helpers ................................................................................................... 24


Q1. What is Area in ASP.NET Core? ............................................................................................................... 24
Q2. Do nested areas are supported by ASP.NET Core? ................................................................................. 24
Q3. How to generate links for controller action under the area? ................................................................. 24
Q4. How can we add Area to ASP.NET Core application? .............................................................................. 24
Q5. What is tag helper in ASP.NET Core?....................................................................................................... 25
Q6. What are the advantages of tag helper? ................................................................................................. 25
Q7. What is different between HTML helper and Tag helper? ...................................................................... 26
Q8. How to add supports for Tag Helper to Razor view? .............................................................................. 26
Q9. How to disable Tag Helper at element level?.......................................................................................... 26
Q10. Can we specify the prefix for tag helper?................................................................................................ 26
Q11. Can we enable directory browsing through the code in ASP.NET Core? ................................................ 27
Q12. What is the use of "UseFileServer" in Configure method of startup class? ............................................ 27

Razor Pages and View Component................................................................................. 28


9
Page

Q1. What are Razor Pages in ASP.NET Core? ................................................................................................. 28


Q2. How can we prevent Razor pages from XSRF/CSRF attack? ................................................................... 28
Q3. How can we do automatic model binding in Razor pages? .................................................................... 28
Q4. How can we be binding the route data in Razor pages? ......................................................................... 29
Q5. What is the use of ViewData attribute in Razor pages? .......................................................................... 29
Q6. How can we apply filters in Razor pages? ............................................................................................... 29
Q7. What is RCL (Razor Class Library) project? .............................................................................................. 30
Q8. What happened if view, partial view, or Razor Page found in both RCL and web application? ............. 30
Q9. What is view component in ASP.NET Core? ............................................................................................ 30
Q10. What are the features provided by the ViewComponent? ..................................................................... 30
Q11. How can we create ViewComponent? .................................................................................................... 30
Q12. What is the default path of view for ViewComponent? ......................................................................... 31
Q13. Can we have invoked view component from the controller? ................................................................. 31

Model Binding and Validations ...................................................................................... 32


Q1. What is Model binding?........................................................................................................................... 32
Q2. How does model binding work in ASP.NET Core application? ................................................................ 32
Q3. What are the characteristics for complex type for binding the value? ................................................... 32
Q4. Can we control the behaviour of Model binding using attribute? .......................................................... 33
Q5. Can we create a custom model binder? If yes how?............................................................................... 33
Q6. How can we use/register custom model binder? ................................................................................... 33
Q7. How can apply custom model binder using ModelBinder attribute? ..................................................... 33
Q8. How can we apply custom model binder globally? ................................................................................. 34
Q9. How can we do model validation with ASP.NET Core? ........................................................................... 34
Q10. How can we check our model is valid or not at the controller level? ..................................................... 34
Q11. Can we validate model manually in Controller class? ............................................................................. 34
Q12. How can we do Client-side validation? ................................................................................................... 35

Globalization and Localization ....................................................................................... 36


Q1. What is Internationalization in ASP.NET Core? ....................................................................................... 36
Q2. What is a resource file naming convention? ........................................................................................... 36
Q3. How can we achieve localization in view? .............................................................................................. 36
10

Q4. How can we access localized resource string in Controller? ................................................................... 37


Page

Q5. Can we localize error messages defined in Data Annotation? ................................................................ 37


Exception Handling and Logging Framework ................................................................. 38
Q1. What is "Developer Exception Page" in ASP.NET Core?.......................................................................... 38
Q2. How can we configure custom exception handling page in ASP.NET Core? ........................................... 38
Q3. How to configure the logging framework in ASP.NET Core?................................................................... 39
Q4. What are the possible values for Log level enum for the Logging framework? ...................................... 39
Q5. How many built-in extension methods provided by logging framework of ASP.NET Core? ................... 40
Q6. What is the use of enum value LogLevel.None? ..................................................................................... 40
Q7. How to set default minimum log level for Logging Framework? ............................................................ 40
Q8. How to define filter rule for Logging framework in ASP.NET Core? ........................................................ 40
Q9. What is log scope in Logging framework? ............................................................................................... 42
Q10. What is third party logging framework that supported by ASP.NET Core? ............................................ 42

Dependency Injection .................................................................................................... 43


Q1. How dependency injection work in ASP.NET Core? ................................................................................ 43
Q2. How many types of service containers available in ASP.NET Core? ....................................................... 43
Q3. How can we inject the service dependency into the controller? ............................................................ 43
Q4. Can we inject the dependency to individual action method of the controller? ..................................... 44
Q5. Can we get service instance without dependency injection in the controller action method? ............. 44
Q6. How to specify service lifetime for register service that added as a dependency? ................................ 44
Q7. How can we inject the service dependency into the View?.................................................................... 45

Security and Filters ........................................................................................................ 47


Q1. What is the use of a filter in ASP.NET Core application?......................................................................... 47
Q2. Explain about the filter types available in ASP.NET Core application ..................................................... 47
Q3. In which sequence all the filters are invoked? ........................................................................................ 47
Q4. How to create a custom filter? ................................................................................................................ 48
Q5. Does the filter support asynchronous implementation? ........................................................................ 48
Q6. How to implement the asynchronous filter in ASP.NET Core? ............................................................... 48
Q7. Explain about the Filter scope? ............................................................................................................... 48
Q8. How to define a Global filter in ASP.NET Core? ...................................................................................... 49
Q9. What is Default order of filter execution?............................................................................................... 49
11

Q10. Can we override the default order of execution of filter in ASP.NET Core? ........................................... 49
Page

Q11. Does the built-in filter also implement the interface IOrderFilter? ........................................................ 50
Q12. Can we cancel execution of filter or short-circuiting filters? .................................................................. 50
Q13. Can we inject the dependency to the filter attribute? ............................................................................ 50
Q14. Can you apply a filter attribute having constructor dependency to the controller or action? ............... 50
Q15. What is exception filter in ASP.NET Core? .............................................................................................. 50
Q16. What is a limitation of Exception filter? .................................................................................................. 51
Q17. What is the use of Result Filter in ASP.NET Core? ................................................................................... 51
Q18. What are Authentication and Authorization? ......................................................................................... 51
Q19. How can we configure built-in identity service for ASP.NET Core application?...................................... 51
Q20. What is the difference between AddDefaultIdentity and AddIdentity? ................................................. 52
Q21. How can we override default configuration? .......................................................................................... 52
Q22. How can we configure windows authentication for ASP.NET Core application?.................................... 53

Unit Testing ................................................................................................................... 55


Q1. What Unit Testing frameworks can be used with ASP.NET Core? .......................................................... 55
Q2. How can we write a unit test with MSTest framework? ......................................................................... 55
Q3. Can we create an MSTest project using command line interface (CLI)? ................................................. 55
Q4. How can we verify the test in MSTest? ................................................................................................... 55
Q5. How can we run the test? ....................................................................................................................... 56
Q6. Can we write a data-driven test using MSTest? ...................................................................................... 56
Q7. How can we write a unit test with xUnit framework? ............................................................................ 57
Q8. How can we verify the test in xUnit?....................................................................................................... 57
Q9. Can we write a data-driven test using xUnit? ......................................................................................... 57
Q10. How can we write a unit test with NUnit framework?............................................................................ 57
Q11. How can we verify the test in NUnit? ...................................................................................................... 58
Q12. Can we write a data-driven test using NUnit?......................................................................................... 58
Q13. What is the use of setup attribute in NUnit framework?........................................................................ 58
Q14. How can we create a test for the controller that have service dependency? ........................................ 58
Q15. What is Mock (or moq) object in a unit test?.......................................................................................... 59

Deployment ................................................................................................................... 60
Q1. What are the different techniques for hosting an ASP.NET Core application?....................................... 60
12

Q2. What is Kestrel? ....................................................................................................................................... 60


Page

Q3. How to use Kestrel in ASP.NET Core application? ................................................................................... 60


Q4. Can we bind TCP socket with Kestrel server?.......................................................................................... 61
Q5. What is HTTP.sys server? ......................................................................................................................... 61
Q6. What are the features are supported by HTTP.sys server?..................................................................... 61
Q7. How to host an application using HTTP.sys server? ................................................................................ 61
Q8. How can host ASP.NET Core application as a Windows service? ............................................................ 61
Q9. What is ASP.NET Core Module? .............................................................................................................. 62

References ..................................................................................................................... 63

13
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
.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.

Q2. What are the features provided by ASP.NET Core?


Ans. Following are the core features that are provided by the ASP.NET Core

• Built-in supports for Dependency Injection


• Built-in supports for the logging framework and it can be extensible
• Introduced new, fast and cross-platform web server - Kestrel. So, a web application can run without IIS,
Apache and Nginx.
• Multiple hosting ways are supported
• It supports modularity, so developer need to include the module that required by the application.
However, .NET Core framework is also providing the meta package that includes the libraries
• Command-line supports to create, build and run the application
• There is no web.config file. We can store the custom configuration into an appsettings.json file
• There is no Global.asax file. We can now register and use the services into startup class
• It has good support for asynchronous programming
• Support WebSocket and SignalR
• Provide protection against CSRF (Cross-Site Request Forgery)

Q3. What is Metapackages?


Ans. The framework .NET Core 2.0 introduced Metapackage that include all the supported package by ASP.NET
code with their dependencies into one package. It helps us to do fast development as we don't require to include
the individual ASP.NET Core packages. The assembly Microsoft.AspNetCore.All is a meta package provide by
ASP.NET core.

Q4. Can ASP.NET Core application work with full .NET 4.x Framework?
14

Ans. Yes. ASP.NET core application works with full .NET framework via the .NET standard library.
Page
Q5. What are advantages of ASP.NET Core over ASP.NET?
Ans. There are following advantages of ASP.NET Core over ASP.NET:

• It is cross-platform, so it can be run on Windows, Linux and Mac.


• There is no dependency on framework installation because all the required dependencies are ship with
our application
• ASP.NET Core can handle more request than the ASP.NET
• Multiple deployment options available withASP.NET Core

Q6. What is the startup class in ASP.NET core?


Ans. Startup class is the entry point of the ASP.NET Core application. Every .NET Core application must have
this class. This class contains the application configuration rated items. It is not necessary that class name must
"Startup", it can be anything, we can configure startup class in Program class.
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.UseStartup<TestClass>();
}

Q7. What is the use of ConfigureServices method of startup class?


Ans. This is an optional method of startup class. It can be used to configure the services that are used by the
application. This method calls first when the application is requested for the first time. Using this method, we can
add the services to the DI container, so services are available as a dependency in controller constructor.

Q8. What is the use of Configure method of startup class?


Ans. It defines how the application will respond to each HTTP request. We can configure the request pipeline
by configuring the middleware. It accepts IApplicationBuilder as a parameter and also it has two optional
parameters: IHostingEnvironment and ILoggerFactory. Using this method, we can configure built-in middleware
such as routing, authentication, session, etc. as well as third-party middleware.

15
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.

Q2. What is the difference between IApplicationBuilder.Use() and


IApplicationBuilder.Run()?
Ans. We can use both the methods in Configure methods of startup class. Both are used to add middleware
delegate to the application request pipeline. The middleware adds using IApplicationBuilder.Use may call the next
middleware in the pipeline whereas the middleware adds using IApplicationBuilder.Run method never calls the
subsequent ore next middleware. After IApplicationBuilder.Run method, system stop adding middleware in
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 request path starts with the given path, middleware on to that branch will execute.

public void Configure(IApplicationBuilder app)


{
app.Map("/path1", Middleware1);
app.Map("/path2", Middleware2);
}

Q4. What is the use of "MapWhen" 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 the result of the given
predicate. we can use predicate of type Func<HttpContext, bool> to map request to the new branch. In the
following example, middleware invoked if request query string has value "id".
16

public void Configure (IApplicationBuilder app)


Page

{
app.MapWhen(context => context.Request.Query.ContainsKey("id"),
Middleware1);
}

Q5. What is middleware?


Ans. It is software which is injected into the application pipeline to handle request and responses. They are just
like chained to each other and form as a pipeline. The incoming requests are passes through this pipeline where
all middleware is configured, and middleware can perform some action on the request before passes it to the next
middleware. Same as for the responses, they are also passing through the middleware but in reverse order.

Q6. How can we configure the pipeline for middleware?


Ans. We can configure ASP.NET Core request/response pipeline using Configure method of Startup class by
using the "Use*" methods. For example

public void Configure (IApplicationBuilder app)


{
app.UseAuthentication();
app.UseStaticFiles();
}

All the middleware(s) are added to ASP.NET Core pipeline in order that they are added.

Q7. What is built-in middleware(s) 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
Cookie Policy Used to configure the cookie policy UseCookiePolicy
17

CORS Configure Cross origin resource AddCors /UseCors


sharing
Page

Diagnostics Configures diagnostics UseDeveloperExceptionPage


Forwarded Headers Forwards proxied headers onto the UseForwaredHeaders
current request
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 available
with only ASP.NET Core 2.1 or later.
MVC Add MVC to request pipeline AddMvc/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
Routing Define route and constrain AddRouting/ UseRouter
Session Add session middleware to request AddSession/UseSession
pipeline
Static Files Add support to 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 middleware describe above from the following link.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1

Q8. Can we write our own middleware?


Ans. Yes, we can write our own middleware. Generally, middleware is encapsulated in a class and expose with
an extension method. There are three easy steps to create middleware

Step 1: Creating a middleware class


public class MyMiddleware
{
private readonly RequestDelegate _next;

public MyMiddleware(RequestDelegate next)


{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
//Write your code here....
18

// invoke the next middleware in the pipeline


Page

await _next(context);
}
}

Step 2: Create an extension of IApplicationBuilder that expose our middleware


public static class MyMiddlewareExtensions
{
public static IApplicationBuilder UseMyMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}

Step 3: register middleware to application using startup.Configure method


public class Startup
{
public void Configure (IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMyMiddleware();
}
}

Q9. What is routing in ASP.NET Core?


Ans. Routing is functionality that map incoming request to the route handler. The route can have values
(extract them from URL) that used to process the request. Using the route, routing can find route handler based
on URL. All the routes are registered when the application is started. There are two type of routing supported by
ASP.NET Core
• The conventional routing
• Attribute routing
The Routing uses routes for map incoming request with route handler and Generate URL that used in response.
Mostly, the application having a single collection of routes and this collection are used for the process the request.
The RouteAsync method is used to map incoming request (that match the URL) with available in route collection.

Q10. How can we configure conventional routing?


Ans. The conventional routing can be configured by setting up routing middleware in Configure method of
startup class.
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

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 above conventional route using the convenience method
UseMvcWithDefaultRoute.
19

app.UseMvcWithDefaultRoute();
Page

We can add route as many as we want.


Q11. What's happened MVC find two disambiguating actions through routing?
Ans. When MVC find two disambiguating actions, MVC choose the best can choose the best match or else
throw an exception.

Q12. What is Attribute routing?


Ans. ASP.NET Core MVC provides a set of attributes to map actions directly with route templates. When we
use attribute routing, we need not required any configuration i.e. we can call app.UseMvc() method in Configure
method of startup class without pass route delegate.

Using Route attribute, we can achieve attribute routing.

[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 route attribute on the controller, they are combined with the route defined on action method.

Q13. 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 controller with attribute route, all actions under this controller are
now attribute routed.

Q14. How can we define a route for areas?


Ans. The areas help us to organize related functionality into a group. For conventional route, MVC provides a
method “MapAreaRoute" to define the route for areas.

app.UseMvc(routes =>
{
routes.MapAreaRoute("default_route", "AreaName", "AreaName/{controller}/{action}/{id?}");
});

For attribute route, MVC provides "Area" attribute to define an area for the route.
Example
[Area("User")]
public class HomeController : Controller
{
20

….
….
Page

}
3
Session and Environment
Settings
Q1. How to 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 ASP.NET Core application, we need to add this package to csproj file and add the Session middleware
to ASP.NET Core request pipeline.

public class Startup


{
public void ConfigureServices(IServiceCollection services)
{
….
….
services.AddSession();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
….
….
app.UseSession();
….
….
}
}

Q2. How many types of session state is available in ASP.NET Core?


Ans. There is two types of state available: InProc or in-memory and OutProc. For the OutProc session, there
are many options available such as SQL server, Redis server, etc.

Q3. How to access the session in ASP.NET Core application?


Ans. Using the HttpContext class, we can access the session in ASP.NET Core application. This class is defined
under Microsoft.AspNetCore.Http namespace. There are three methods available to set the value to the session
• Set: It accepts byte array as argument and store byte array to a session
21

• SetInt32: It is an extension method that accepts the int. Internally, it converts an integer value to a byte
Page

array and call set method


• SetString: It is an extension method that accepts the string. Internally, it converts a string value to a byte
array and call set method

Similarly, there is three methods to get the session value. All the method accepts the key name as a parameter.
• Get: It returns the byte array
• GetInt32: It returns the integer value
• GetString: It returns the string value

Example:
string name = "Jignesh Trivedi";
HttpContext.Session.Set("MyName" ,Encoding.Default.GetBytes(name));

string name1 = Encoding.Default.GetString(HttpContext.Session.Get("MyName"));

Q4. Why Session is stored in form of 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.

Q5. Is there any sequence to call UseSession() method in Configure method?


OR
Is session being enable if UseSession() method call last in Configure method
of startup class?
Ans. There is no such sequence to call UseSession method in Configure method of startup class however this
method must call before the UseMvc method.

Q6. Can we store the Complex data into the session?


Ans. Yes, we can store the complex data to the session. The idea behind to store complex data is to serialize
the complex object and convert it into a string and stored in the session.

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();
22

}
}
Page
Q7. How to set an environment variable?
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 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

Q8. Key for environment variable is case-sensitive?


Ans. It is case-sensitive for MacOS and Linux whereas it is case-insensitive for windows 10.

Q9. How determine the value of an environment variable programmatically?


Ans. Using Environment.GetEnvironmentVariable method, we can get the value of environment variable
programmatically.

string value = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

Q10. What are the various JSON files available in ASP.NET Core?
Ans. There are following JSON files in ASP.NET Core:

• global.json
• launchsettings.json
• appsettings.json
• bundleconfig.json
• bower.json
• package.json

Q11. What is the use of “launchsettings.json” file?


Ans. This JSON file contains the project specific settings with each Visual Studio profile that configured to
launch the application. In this file, we can also specify the version of the framework used by the application for
compilation and debugging. It also contains information about environment variables that can be used.

Q12. What is the use of "appsettings.json" file?


Ans. This file is used to define application related setting such as connection string, any other custom settings.
In earlier version i.e. ASP.NET, we are defining such setting into the web.config file.

Q13. What is the use of "bower.json" file?


Bower is the package manager for the web. So, this file holds the reference of the dependencies. The bower.json
file holds the reference of dependencies that are provided by the Bower package manager.
23
Page
4
Areas and Tag Helpers
Q1. What is Area in ASP.NET Core?
Ans. The area has allowed us to organize related functionality into a group. It provides the physical grouping
and every group have their own set of model, view and controller. It allows us to define the same controller name
in different areas.

Q2. Do nested areas are supported by ASP.NET Core?


No. Currently, nested areas are supported by the ASP.NET Core directly but it can be achieved by implement
IViewLocationExpander. This interface helps us to modify view locations that search by the view engine.

Q3. How to generate links for controller action under the area?
To identify the controller under view, we need to pass area name in route argument.
Example:
@Html.ActionLink("Test Area", "Index", "Home", new { area = "Account" })

Q4. How can we add Area to ASP.NET Core application?


We can create Area by right click on solution, select Add >> Area option. This creates a new area folder and under
this folder Model, view, controller folder is created.

24
Page
Q5. What is tag helper in ASP.NET Core?
Ans. It is a feature provided by Razor view engine that enables us to write server-side code to create and render
the HTML element in view (Razor). The tag-helper is C# classes that used to generate the view by adding the HTML
element. The functionality of tag helper is very similar to HTML helper of ASP.NET MVC.

Example:
//HTML Helper
@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", placeholder = "Enter
Your First Name" })

//content with tag helper


<input asp-for="FirstName" placeholder="Enter Your First Name" class="form-control" />

//Equivalent HTML
<input placeholder="Enter Your First Name" class="form-control" id="FirstName" name="FirstName"
value="" type="text">

Q6. What are the advantages of tag helper?


Ans. There are following advantages of tag helpers:

• The tag helper looks same as 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
25
Page
Q7. What is different between HTML helper and Tag helper?
Ans. The functionality of HTML helper and tag helper is nearly the same but there is some minor difference
between same.

HTML Helper Tag Helper


HTML helper starts with @ symbol that indication There is no such symbol or representation in tag
of staring of code helper
The Html helper used the anonymous object to Tag helper is used as HTML attribute, no such
represent the HTML attribute such as class, id, etc. anonymous object is required
They are very difficult to understand and maintain They are very much clear so easy to understand
and maintain. The HTML code is more readable as
compare to HTML helper
The intellisense is very difficult with HTML helper Visual Studio provides very rich intellisense for tag
helper

Q8. How to add supports for Tag Helper to Razor view?


Ans. Using directive @addTagHelper define in _ViewImports.cshtml file, we can add the tag helper into the
Razor. The _ViewImports.cshtml file used to provide the namespace that can be used in all the views.

Syntax:
@addTagHelper {name of the tag helper} {assembly name of the tag helper}

Example: _ViewImports.cshtml
@using TagHelper
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

In above example, we have to used wildcard character (*). It means that it adds the tag helpers define in
"Microsoft.AspNetCore.Mvc.TagHelpers" assembly to Razor view.

Q9. How to disable Tag Helper at element level?


Ans. We can disable Tag Helper at element level using the opt-out character ("!"). This character must apply
opening and closing Html tag.
Example
<!span asp-validation-for="phone" class="divPhone"></!span>

Q10. Can we specify the prefix for tag helper?


Ans. Using @tagHelperPrefix, we can specify the tag prefix. This tag prefix also needs to specify into
_ViewImports.cshtml file.

Example:
Views/_ViewImports.cshtml
26

@tagHelperPrefix th:
Page

index.cshtml
<div class="form-group">
<th:label asp-for="Firstname" class="col-md-6"></th:label>
</div>

Q11. 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 startup class.

Example:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
...
services.AddDirectoryBrowser();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
...
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new
PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
RequestPath = "/ProjectImages"
});
...
...
}
}

Q12. What is the use of "UseFileServer" in Configure method of startup class?


Ans. It is combination of UseDefaultFiles, UseStaticFiles and UseDirectoryBrowser. The "UseDefaultFiles"
method enable the website to serve a default page without providing qualified URI. The "UseStaticFiles" method
enable the website to server static files the stored in the project default directory. The default directory is
"<content_root>/wwwroot", but we can change it via UseWebRoot method. The UseDefaultFiles method must
be called before UseStaticFiles method.
27
Page
5
Razor Pages and View
Component
Q1. What are 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 are start with the @page directive. This directive handle request directly without passing through
the controller. The Razor pages may have code behind file, but it is not really code-behind file. It is class inherited
from PageModel class.

Q2. How can we prevent Razor pages from XSRF/CSRF attack?


Ans. We do not require to write any code to prevent Razor pages from XSRF/CSRF attack. The Antiforgery token
generation and validation are done automatically in Razor Pages.

Q3. How can we do automatic model binding in Razor pages?


Ans. The Razor pages provide the option to bind property automatically when posted the data using
BindProperty attribute. By default, it only binds the properties only with non-GET verbs. we need to set
SupportsGet property to true to bind a property on getting request.

Example:
public class Test1Model : PageModel
{
[BindProperty]
public string Name { get; set; }
}
28
Page
Q4. How can we be binding the route data in Razor pages?
Ans. The route data that used with Razor pages can be defined with the @Page directive. We can also define
route parameter constrain such as the type of route data.
Example:
@page "{id}"

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"]

Q5. What is the use of ViewData attribute in Razor pages?


Ans. This attribute is introduced in ASP.NET Core 2.1. Any Razor page model property decorated with ViewData
attribute, their value is stored in ViewDataDictionary with property name as the key, so this property can be access
in view via the Model property or the ViewData dictionary.
Example
[ViewData]
public string MyData { get; set; } = "This is Test";
In view
<h2>@Model.MyData</h2>
<h2>@ViewData["MyData"]</h2>

Q6. 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());
});
}

2) Apply Filter to individual page:


[MyPageFilter()]
public class ContactModel : PageModel
{
...
29

}
Page
Q7. What is RCL (Razor Class Library) project?
Ans. It is introduced with ASP.NET Core 2.1 and it allows us to reuse Razor pages/views (UI element) across
multiple projects. It includes Razor pages, view components, data model, Razor views, and controllers. We can
also create NuGet packages for this library.

Q8. 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.

Q9. What is view component in ASP.NET Core?


Ans. It is a newly added feature and very similar to partial view. It is more powerful than the partial view. View
component can work with both ASP.NET Core MVC and Razor pages. It is not used the data binding, but it renders
based on the data provided. There is two part of view component: one is class and another return result (View in
most cases).

Q10. What are the features provided by the ViewComponent?


Ans. The ViewComponent provides the following features:
• It follows SOC (separation-of-concerns) so provide maintainability and testability
• Also invoked from the Layout page
• It renders in chunk rather than a whole response
• May contains business logic and parameter
• It supports constructor dependency injection
• It does not take part in the controller life cycle

Q11. How can we create ViewComponent?


Ans. There is two part of view component: one is view component class and another return result (View in
most cases). View component class is very similar to the controller class. It must be public, non-abstract and non-
nested. The view component class must inherit from a ViewComponent base class or decorated with
ViewComponent attribute.

public class CustomerList: ViewComponent


{
public async Task<IViewComponentResult> InvokeAsync(int noOfEmployee)
{
...
...
return View();
}
}
30

optionally, we can decorate the class with ViewComponent attribute. Here it is not necessary that class name is
same as view component name. We can also set view component by using name property.
Page
[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 view component.

@await Component.InvokeAsync("CustomerList", new { noOfEmployee = 5 })

Q12. What is the default path of view for ViewComponent?


Ans. Same as controller, views are searched in following location
• View/{Controller Name}/Components/{View Component name}/{View Name}
• Views/Shared/Components/{View Component Name}/{View Name}

Q13. Can we have invoked view component from the controller?


Ans. Yes, we can invoke view component from the controller.

Example:
public IActionResult IndexVC()
{
return ViewComponent("CustomerList", new { noOfEmployee = 3 });
}

31
Page
6
Model Binding and Validations
Q1. What is Model binding?
Ans. Model binding is a feature that maps the data from HTTP request to the parameters of the controller
actions method. The parameters can be a simple type like int, double, string or can be a complex type.

Q2. How does model binding work in ASP.NET Core application?


Ans. ASP.NET Core retrieves a route from the HTTP request and determines the action method be called. Then
it binds the route data to the action method's parameters. It binds the request data to the parameter by name. If
the parameter is a complex type, the all the properties must have public settable. Following are the data source
that used by a model binder to bind the value to the parameter.
• Form values - it is form data, that go with HTTP request, using POST method
• Route values - set of route values provided by MVC routing
• Query strings - data is part of the URL.
Example:
URL: http://abcd.com/my/edit/2
[Route("my/edit/{id?}")]
public IActionResult Edit(int? id)
{

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 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 for complex type for binding the value?
Ans. For binding to happen
• The class must have public and default constructor (without parameter)
32

• Properties that need to bind must be writable and public


Page

Model binder uses default constructor to initialize a complex type.


Q4. Can we control the behaviour of Model binding using attribute?
Ans. Yes, ASP.NET Core MVC provides some attribute that helps us to control the behaviour of Model
binding. Following are the attributes.
• BindNever: It tells model binder to not bind value with parameter
• BindRequired: This attribute mark parameter as required, and it adds error in the model state if binding
not found
• FromHeader: It defines the binding source as a request header
• FromQuery: It defines the binding source as a query string
• FromRoute: It defines the binding source as route data
• FromForm: It defines the binding source as a form data posted
• FromServices: It defines the binding source as services that injected as a dependency
• FromBody: Model binder find the parameter value for request body
• ModelBinder: It tells the MVC to use a custom model binder to bind the parameter value

Q5. Can we create a custom model binder? If yes how?


Ans. Yes, we can create a custom model binder with ASP.NET Core MVC. Using custom model binder, we can
extend model binder functionality. It required when we need to transform the input prior to binding.

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();
}
}

Q6. How can we use/register custom model binder?


Ans. There are two ways to register or use custom model binder
• Using ModelBinder attribute
• By defining binder provider and register it to ConfigureServices method of the startup class

Q7. How can apply custom model binder using ModelBinder attribute?
Ans. There are two ways to apply custom model binder using ModelBinder attribute.
1) Apply ModelBinder attribute to the model class
Example:
[ModelBinder(BinderType = typeof(CustomModelBinder))]
public class User
{
//...
33

}
Page

2) Apply ModelBinder attribute to individual action method


Example:
public IActionResult Contact([ModelBinder(BinderType = typeof(CustomModelBinder))] User
u)
{
}

Q8. How can we apply custom model binder globally?


Ans. We can apply custom model binder globally by registering binder to ConfigureServices method of startup
class so model binder is available for all the action method.
We must create binder provider (the class that implement IModelBinderProvider interface) to register custom
model binder globally.

Example:
public class CustomModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(User))
return new CustomModelBinder();

return null;
}
}

public void ConfigureServices(IServiceCollection services)


{
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new CustomModelBinderProvider());
});
}

Q9. How can we do model validation with ASP.NET Core?


Ans. ASP.NET Core also supports model validation using Data annotation. There are many built-in attributes
are available such as Required, StringLength, Range, etc. and you can also create a custom validation attribute to
validate our model.

Q10. 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.

Q11. Can we validate model manually in Controller class?


Ans. Base controller class ControllerBase has method "TryValidateModel" that help us to validate model
manually in Controller class. This method returns true if the model is valid.
34
Page
Q12. How can we do Client-side validation?
Ans. The data annotation has built-in support for client-side validation. The client-side validation performs
using jQuery Unobtrusive Validation script. The tag helper and Html helper have validation attributes that render
HTML 5 data-attribute in the element that required for validation. Then jQuery Unobtrusive Validation parses
data- attribute and perform the validation on the control when submitting the form.

Example:
<div class="col-md-10">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>

To perform the client-side validation, you must include jQuery and jQuery Unobtrusive Validation script file.

35
Page
7
Globalization and Localization
Q1. What is Internationalization in ASP.NET Core?
Ans. It involves Globalization and Localization. The 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. application will display data based on selected language.

Q2. What is a resource file naming convention?


Ans. Resource file name same as controller and view name with full type except for assembly name. For
example, HomeController within demoApp.Controllers namespace, the naming convention for this file for English
resource file is Controllers.HomeController.en-Us.resx.

Alternatively, we can put resource file under similar folder as naming provided i.e. under folder
Resources/Controllers/HomeController.en-US.resx

We can set resource file path in ConfigureService method.

Q3. How can we achieve localization in view?


Ans. The ASP.NET Core provides the IViewLocalizer service that is used to localize string into view. This interface
finds the resource file under view file path and the file name is same as the view name.

Example:
@using Microsoft.AspNetCore.Mvc.Localization

@inject IViewLocalizer Localizer


<div>
@Localizer[“TestAppText”]
</div>
36

Also, we need to register AddViewLocalization service in ConfigureServices method of startup class.


Page

public void ConfigureServices(IServiceCollection services)


{
services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
}

There is no option for globally shared resource file but it can be achieved by using IHtmlLocalizer service.

Q4. How can we access localized resource string in Controller?


Ans. ASP.NET Core provides IStringLocalizer and IStringLocalizer<T> interface as dependency injection that use
ResourceManager and ResourceReader to provide culture-specific resources at runtime. Using this interface, we
can access localize string in the controller.

Example:
public class MyController : Controller
{
private readonly IStringLocalizer<MyController> _localizer;

public AboutController(IStringLocalizer<MyController> localizer)


{
_localizer = localizer;
}

[HttpGet]
public string Get()
{
return _localizer["Title"];
}
}

Q5. Can we localize error messages defined in Data Annotation?


Ans. Yes, it can localize using the service IStringLocalizer and register the service using
AddDataAnnotationsLocalization method in ConfigureServices method of Startup class.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
. AddDataAnnotationsLocalization();
}

Example
public class ModelClass
{
[Required(ErrorMessage = "RequiredName")]
public string Name { get; set; }
}
37
Page
8
Exception Handling and
Logging Framework
Q1. What is "Developer Exception Page" in ASP.NET Core?
Ans. It is a feature that shows detailed information about the exception. This can be enabled using 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
{
...
}
...
...
}

Q2. How can we configure custom exception handling page in ASP.NET Core?
Ans. Using the middleware "Exception Handler", we can add custom exception handling page in ASP.NET Core.
We can add this middleware by calling IApplicationBuilder.UseExceptionHandler method in Configure method of
startup class.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
38

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

app.UseHsts();
}
...
...
}

Note that whatever route you mention here that must available in the application.

Q3. How to configure the logging framework in ASP.NET Core?


Ans. There are two easy steps to add logging support to ASP.NET Core application
1. We need to dependency of "Microsoft.Extensions.Logging" to csproj file, however, this dependency added
by default for .NET framework 2.0 and above
2. Next step is to add provider extension method to configure logging method of WebHostBuilder instance
under the main method of program class

public class Program


{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{

logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>();
}

Q4. 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)
39
Page
Q5. How many built-in extension methods provided by 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 at specifying log level. This is a base method and the methods
describe above are called this method internally with different log level

Q6. What is the use of enum value LogLevel.None?


Ans. When minimum log level is specified as LogLevel.None, Logging framework suppress all the log.

Q7. How to set default minimum log level for Logging Framework?
Ans. Using LoggingBuilderExtensions.SetMinimumLevel method, we can set a minimum log level and it
effective only if no rules are defined either by code or configuration. This method calls from the main method of
program class.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.SetMinimumLevel(LogLevel.Warning);
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>();

In the above example, minimum log level is set to warn so, Logging framework ignores the log message that below
mentioned warning level.

Q8. How to define filter rule for 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
JSON configuration file and add a configuration section to the logging framework. In the following code example,
I have followed steps mention here.

Example:
40

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
Page

.ConfigureAppConfiguration((hostingContext, config) =>


{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>();

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"
}
}
}

Above example creates five filter rules


• One rule for Debug provider
• Three rules for Console Provider
• One rule for all provider

The same thing can be achieved using the C# code using the AddFilter method.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddFilter("System", LogLevel.Debug);
logging.AddFilter<Microsoft.Extensions.Logging.Debug.DebugLoggerProvider>("System",
LogLevel.Information);
41

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>();

Q9. What is log scope in Logging framework?


Ans. It allows us to group a set of logical operations within the log scope, so logging framework attached same
data to each log of this set. To use log scope, first, we need to enable scopes for the provider.

.ConfigureLogging((hostingContext, logging) =>


{
...
...
logging.AddConsole(options => options.IncludeScopes = true);
...
...
}

In controller Action
public IActionResult TestMethod()
{
using (_logger.BeginScope("Log Scope Start"))
{
_logger.LogInformation("Example Scope");
_logger.LogWarning("My Scope");
}
return View();
}

Q10. What is third party logging framework that 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
42

• Sentry
• Serilog
Page

• Stackdriver
9
Dependency Injection
Q1. How 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 in Controllers, Views and Models. The services that are added to the service
container are available as dependency service.

Q2. How many types of service containers available in ASP.NET Core?


Ans. There is two type of service container available in ASP.NET Core: Application Services and Framework
Services. The framework services are service that is provided by the ASP.NET Core such as ILoggerFactory etc. The
application services are the customs services created a base on our requirement.

Q3. How can we inject the service dependency into the controller?
Ans. There are three easy steps to add custom service as a dependency into the controller.
Step 1: Create the service
public interface IHelloWorldService
{
string SaysHello();
}

public class HelloWorldService: IHelloWorldService


{
public string SaysHello()
{
return "Hello ";
}
}

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>();


}
43
Page

Step 3: Use this service as a dependency in the controller


public class HomeController: Controller
{
IHelloWorldService _helloWorldService;
public HomeController(IHelloWorldService helloWorldService)
{
_helloWorldService = helloWorldService;
}
}

Q4. Can we inject the dependency to individual action method of the


controller?
Ans. Yes. Using the “FromServices" attribute, we can inject the dependency to 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();
}

Q5. Can we get service instance without dependency injection in the


controller action method?
Ans. Yes. We can retrieve the service from the ASP.NET Core service container. Using method "GetService" of
"HttpContext.RequestServices" property, we can get dependent services configured with Service container. This
is also known as property injection.
Example:
public IActionResult Index1()
{
var helloWorldService =
(IHelloWorldService)this.HttpContext.RequestServices.GetService(typeof(IHelloWorldService));
ViewData["MyText"] = helloWorldService.SaysHello() + "Jignesh Trivedi!";
return View("index");
}

Q6. How to specify service lifetime 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 the cleaning these dependencies, it will
take care by ASP.NET Core framework. There is three type 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 AddSingleton method of IServiceCollection. ASP.NET Core creates service instance at
44

the time of registration and subsequence request use this service instance. Here, we do not require to implement
Page

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 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 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();
}

public class HelloWorldService: IHelloWorldService


{
public string SaysHello()
{
return "Hello ";
}
}

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>();


}
45

Step 3: Inject the dependency to view using @inject directive. Here we need to pass service type and instance
name that is used to access the service method.
Page

@inject <type> <instance name>


Example:
@{
ViewData["Title"] = "DIToView";
}
@inject DepedencyInjectionExample.Service.IHelloWorldService helloWorldService

<h4>DI To View</h4>

<h5>
@helloWorldService.SaysHello() Reader!!!
</h5>

46
Page
10
Security and Filters
Q1. What is the use of a filter in ASP.NET Core application?
Ans. Filters allowed us to execute custom code after and before executing the action method. They are invoked
various stage of application life-cycle. There are many built-in filters are available with ASP.NET Core application
such as Authorize, HttpGet, HttpPost etc.

Q2. Explain about the filter types available in ASP.NET Core application
Ans. Following filter types provided by ASP.NET Core Application.
• Authorization filters: It helps us to find out whether the user is authorized for the current request. This
executes first in request pipeline.
• Resource filters: It executes immediately after the Authorization filters and before model binding
happened.
• Action filters: It executes before and after the controller action method execute.
• Exception filters: It is used to handle the exception
• Result filters: It executes before and after the execution of controller action results.

Q3. In which sequence all the filters are invoked?


Ans. The following diagram shows the filter sequence, in which they are executed.

47
Page
Q4. How to create a custom filter?
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 action executed.

using Microsoft.AspNetCore.Mvc.Filters;
namespace CustomFilters
{
public class MyActionFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
}
}

Q5. Does the filter support asynchronous implementation?


Ans. Yes, filter supports asynchronous implementation. With asynchronous filters, there is only one method
OnStageExecutionAsync to implement.

Q6. How to implement the asynchronous filter in ASP.NET Core?


Ans. To implement the asynchronous filter, the class must implement IAsyncActionFilter interface. Following
is the example.

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
}
}
}

Q7. Explain about the Filter scope?


Ans. There are three different scopes for add filter to ASP.NET request pipeline:
• To Action method: It is applied to action which decorated with the action filter
• To controller: It is applied to all action methods of the controller which decorated with the action filter
48

• Global filter: It is allied to the all the controller 's action methods
Page
Q8. How to define a Global filter in ASP.NET Core?
Ans. To register filter that applied globally, we need to add a filter to MvcOption.Filters collection in
ConfigureServices method of startup class. We can add a filter by instance or by type. Following is code example.

public void ConfigureServices(IServiceCollection services)


{
...
...
services.AddMvc(options =>
{
//an instant
options.Filters.Add(new MyActionFilter());
//By the type
options.Filters.Add(typeof(MyActionFilter));
});
}

Q9. What is Default order of filter execution?


Ans. The global filter first applied on to the request and then the controller level filter applied and finally, action
method level filter applied. Following diagram shows the default order of execution of filters in a different scope.

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 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:
using Microsoft.AspNetCore.Mvc.Filters;
49

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, built-in filter implements the IOrderFilter interface and default value for order property is set to 0
(zero).

Q12. Can we cancel execution of filter or short-circuiting filters?


Ans. Yes, by setting up the Result property of the context parameter (ActionExecutingContext or
ActionExecutedContext), we can short-circuit the filters.
Example:
public void OnActionExecuted(ActionExecutedContext context)
{
context.Result = new ContentResult()
{
Content = "Short circuit filter"
};
}

Q13. Can we inject the dependency to the filter attribute?


Ans. The filter that applied directly to the controller or its action cannot have constructor dependency. This is
a limitation of filter attribute. But there is a way to overcome this limitation.

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 filter attribute. But there is a way to overcome this limitation. There is built-in attribute available,
with help of them we can apply such filter to controller or action method. Following are the built-in attribute.
• ServiceFilterAttribute
• TypeFilterAttribute

Q15. What is exception filter in ASP.NET Core?


Ans. It is used to handle the exception that occurred during the execution code and it provides a place on that
we can do something before anything written to the response body. It helps us to apply error handling policy for
the application. It implements either IAsyncExceptionFilter or IExceptionFilter interface. Both the interface has a
single method that needs to override.
50

Example:
Page

public class CustomExceptionFilterAttribute : Attribute, IExceptionFilter


{
public void OnException(ExceptionContext context)
{
var exception = context.Exception;
//Do something with exception

// log exception here....


var result = new ViewResult { ViewName = "Error" };
context.Result = result;
context.ExceptionHandled = true;
}
}

Q16. What is a limitation of Exception filter?


Ans. Exception filters are not able to handle exceptions when they occurred in following are
• Controller Constructor
• Another action filter such as Resource filters, Result filters, etc.
• Result execution
• Model binding

Q17. What is the use of Result Filter in ASP.NET Core?


Ans. It is used to run the custom code before and after the execution of the action result. It is executed if the
action method has been successfully executed. If we want to add the logic that executed before and after a view
result is executed, a result filter can be used. For example, modify view result before render the view.

Q18. What are Authentication and Authorization?


Ans. Authentication is a process of checking user identity and user identity can be checked against any trusted
source such database or other 3rd party services such as Facebook, LinkedIn, etc.

Authorization is a process of checking user rights i.e. determines whether user able to 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.

Q19. How can we configure built-in identity service for ASP.NET Core
application?
Ans. By calling AddDefaultIdentity or AddIdentity in ConfigureService method of startup class, we can add built-
in identity service to the request pipeline. This service can be enabled by calling UseAuthentication in Configure
method of startup class.

Using the following code, we can Configure identity middleware.

public void ConfigureServices(IServiceCollection services)


51

{
...
Page

...
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
...
app.UseAuthentication();
...
}

By decorating controller or action method with Authorize attribute that you apply authorization.

Q20. What is the difference between AddDefaultIdentity and AddIdentity?


Ans. Both are added default identity system configuration for user and role, however, AddDefaultIdentity
method add more default configuration to the system such as default login page, registration page, etc. We can
configure a default configuration with the AddIdentity method.

Q21. How can we override default configuration?


Ans. ASP.NET Core allows us to override the default configuration by changing the value of IdentityOption in
ConfigureServices method of startup class. If we are not adding configuration, ASP.NET Core application use the
default configuration.

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)
52

• ConfigureApplicationCookie(Cookie settings for Application)


Page
Q22. How can we configure windows authentication for ASP.NET Core
application?
Ans. We can configure Windows authentication in ASP.NET Core application by one of the following ways
1) Configure windows authentication when they created
We can configure Windows authentication for ASP.NET Core application when it created by either Visual Studio
or using CLI.

>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 "Enable Windows Authentication" checkbox.

53
Page
3) We can also configure it through IIS
Select the application and Go to Feature view >> select "Authentication" module and enable Windows
Authentication.

54
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 MSTest framework?


Ans. To write a unit test using 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 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 MSTest project with CLI.
dotnet new MSTest

Q4. How can we verify the test in MSTest?


Ans. We can verify the test using the Assert class. This class has a couple of methods that helps us to verify the
actual result with the expected result. For example, the AreEqual method used to verify specified values must
equal otherwise it throws an exception.
Example:
[TestMethod]
public void TestMethod1()
55

{
int expected = 1;
Page

int actual = 1;
Assert.AreEqual(expected, actual);
}

Q5. How can we run the test?


Ans. We can run test either from CLI or Test Explore. Using the following command, we can run all the test
within the project.
dotnet test

We can also run the test from test explore or from individual test method from the code reference.

Q6. Can we write a data-driven test using MSTest?


Ans. Yes, we can write data-driven test in MSTest by using DataTestMethod and DataRow attribute. The
DataTestMethod attribute tells the test framework that this is test method and the DataRow attribute specify the
input value to run the unit test.

[DataTestMethod]
[DataRow(1,"Test")]
[DataRow(2, "Test 1")]
public void TestMethod2(int Id, string name)
{
//do something
}
56
Page
Q7. How can we write a unit test with xUnit framework?
Ans. The xUnit is open source and community-focused unit testing framework. To write a unit test using xUnit
framework, create a class and create test method under this class as many as you want but denote the methods
with Fact attribute.

[Fact]
public void Test1()
{
//do something.
}

Q8. How can we verify the test in xUnit?


Ans. We can verify the test using the Assert class. This class has a couple of methods that helps us to verify
the actual result with the expected result. For example, "Equal" method is used to verify that specified values
must equal otherwise it throws an exception.
Example:
[Fact]
public void Test1()
{
string test1 = "Test1";
string test2 = "Test2";
Assert.Equal(test1, test2);
}

Q9. Can we write a data-driven test using xUnit?


Ans. Yes, we can write data-driven test in xUnit by using Theory and InlineData attribute. The Theory attribute
tells the test framework that this is test method and the InlineData attribute specify the input value to run the
unit test.
Example:
[Theory]
[InlineData(1, "Test Data 1")]
[InlineData(2, "Test Data 2")]
public void Test2(int id, string name)
{
//Do something
}

Q10. How can we write a unit test with NUnit framework?


Ans. NUnit is an open source unit test framework that supports all the .NET languages. It is very similar to
MSTest. The template for NUnit is not by default available, so we need to install the template using CLI or using
NuGet package manager.
//Using CLI
>dotnet new - I NUnit3.DotNetNew.Template

//Using NuGet package manager


57

PM> Install-Package NUnit -Version 3.9.0


Page
To write a unit test using NUnit framework, create a class that denote with TestFixture attribute and create test
method under this class as many as you want but denote the methods with "Test" attribute.
Example:
[TestFixture]
public class TestClass
{
[Test]
public void Test1()
{
//Do something
}
}

Q11. How can we verify the test in NUnit?


Ans. We can verify the test using the Assert class. This class has a couple of methods that helps us to verify the
actual result with the expected result. For example, "AreEqual" method is used to verify that specified values must
equal otherwise it throws an exception.
Example:
[Test]
public void Test1()
{
string test1 = "Test1";
string test2 = "Test2";
Assert.AreEqual(test1, test2);
}

Q12. Can we write a data-driven test using NUnit?


Ans. Yes, we can write data-driven test in NUnit by using TestCase attribute. The TestCase attribute specify the
input value to run unit test.
[TestCase(1, "TestData 1")]
[TestCase(2, "TestData 2")]
public void TestMethod(int Id, string name)
{
//do something
}

Q13. What is the use of setup attribute in NUnit framework?


Ans. This attribute is used to identify the method that called before executing of each test. In another word, it
helps us to write test initialization that required before test executes.

Q14. How can we create a test for the controller that have service
dependency?
Ans. We can get the service instance object using the GetService method of service provider class. To test the
controller having such a dependency, we can create an instance of service provider class and get required service
58

instance.
Page
In the following example, Controller having a dependency on ILogger service. So, I have created an object of the
service provider and using service provider class object of such services can be created.

public void TestMethod1()


{
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();

var factory = serviceProvider.GetService<ILoggerFactory>();

var logger = factory.CreateLogger<HomeController>();


HomeController home = new HomeController(logger);
...
...
}

Q15. What is Mock (or moq) object in a unit test?


Ans. The mock object is a dummy object that acts as a real object and this object can be controlled in test code.
The moq (https://github.com/moq/moq4) is a library which allows creating mock objects in code. This library is
also available on NuGet (https://www.nuget.org/packages/Moq/). This mock object supports all three test
frameworks.

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
}

59
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

• Hosted with IIS/Azure App service


• Hosted with Nginx (Linux)
• Hosted with Apache (Linux)
• Hosted as a Windows service
• Hosted using HTTP.sys / Kestrel server

Q2. What is Kestrel?


Ans. The Kestrel is a web server that supports cross-platform. It included in the default in ASP.NET Core project
templates. It supports the following features:
• HTTPS
• Opaque upgrade used to enable WebSockets
• Unix sockets for high performance behind Nginx

Q3. How to use Kestrel in ASP.NET Core application?


Ans. The definition of Kestrel web server is under Microsoft.AspNetCore.Server.Kestrel package, however, it is
included in the Microsoft.AspNetCore.App meta package.

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();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


60

WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
Page

.UseKestrel(options =>
{
//set properties of Kestrel server
});
}

Q4. Can we bind TCP socket with Kestrel server?


Ans. Yes. Using Listen method, we can bind to a TCP socket and also, we can configure the SSL certificate.
Same as it has ListenUnixSocket method to bind Unix socket.

Q5. What is HTTP.sys server?


Ans. It is a Windows-based web server for ASP.NET Core. It is an alternative to Kestrel Server and it has some
features that are not supported by Kestrel. It does not work with IIS due to it is an incompatibility with the ASP.NET
Core modules.

Q6. What are the features are supported by HTTP.sys server?


Ans. Following features are supported by HTTP.sys server.
• Windows Authentication
• Response caching
• WebSockets
• Direct file transmission
• Port sharing
• HTTPS with SNI (Server Name Indication)
• HTTP/2 over TLS
It supports Windows 7 and Windows Server 2008 R2 and later

Q7. How to host an application using HTTP.sys server?


Ans. Following are the step to configure HTTP.sys server for ASP.NET Core application
• Add reference to Microsoft.AspNetCore.Server.HttpSys assembly that contains the definition of HTTP.sys
server, however, this library included in Meta package.
• Configure HTTP.sys server using UseHttpSys method of WebHostBuilder in the main method of Program
class. We can also specify the options for HTTP.sys server.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseHttpSys(options =>
{
//specify the option for HTTP.sys server
});

Q8. How can host ASP.NET Core application as a Windows service?


Ans. Followings are the step to host ASP.NET Core application as a Windows service
• Install Microsoft.AspNetCore.Hosting.WindowsServices package from NuGet
61

• This package contains RunAsService extension method that specified web application hosted as windows
Page

service
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args)
.Build()
.RunAsService();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}

We can also handle service start / stop event for windows service.

Q9. What is ASP.NET Core Module?


Ans. It allows the application to run behind IIS in a reverse proxy configuration, however, IIS provides advanced
web app security and manageability features. It can be work only with windows version Windows 7 or later and
Windows Server 2008 R2 or later. This module is incompatible with HTTP.sys.

62
Page
References

This book has been written by referring to the following sites:

1. https://docs.microsoft.com/en-us/aspnet/core - Microsoft Docs - ASP.NET Core


2. https://stackoverflow.com/questions/tagged/asp.net-core - Stack Overflow - ASP.NET Core
3. https://www.dotnettricks.com/learn/aspnetcore - Dot Net Tricks – ASP.NET Core

63
Page

You might also like