ASP.NET Core Interview Questions And Answers
ASP.NET Core Interview Questions And Answers
All rights reserved. No part of this book can be reproduced or stored in any retrieval system or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the Dot Net Tricks Innovation Pvt. Ltd.
The author of this book has tried their best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author or Dot
Net Tricks Innovation Pvt. Ltd. will not be liable for any damages, incidental or consequential caused directly or
indirectly by this book.
Further, readers should be aware that the websites or reference links listed in this book may have changed or
disappeared between when this book was written and when it is read.
All other trademarks referred to in this book are the property of their respective owners.
Release History
• Initial Release 1.0 - 30th Nov 2018
• Second Release 1.1 - 4th Jan 2019
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.
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).
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
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
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.
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.
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.
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.
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 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.
• [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
Q11. What's happened MVC find two disambiguating actions through routing? ........................................... 20
Page
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
Deployment ................................................................................................................... 60
Q1. What are the different techniques for hosting an ASP.NET Core application?....................................... 60
12
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.
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:
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.
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.
{
app.MapWhen(context => context.Request.Query.ContainsKey("id"),
Middleware1);
}
All the middleware(s) are added to ASP.NET Core pipeline in order that they are added.
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
await _next(context);
}
}
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
[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.
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.
• SetInt32: It is an extension method that accepts the int. Internally, it converts an integer value to a byte
Page
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));
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
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
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" })
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" })
//Equivalent HTML
<input placeholder="Enter Your First Name" class="form-control" id="FirstName" name="FirstName"
value="" type="text">
• 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.
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.
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"
});
...
...
}
}
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.
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"]
}
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.
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.
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.
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
To create a custom model binder, the class must implement IModelBinder interface.
Example:
public class CustomModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}
Q7. How can apply 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
Example:
public class CustomModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(User))
return new CustomModelBinder();
return null;
}
}
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.
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.
Alternatively, we can put resource file under similar folder as naming provided i.e. under folder
Resources/Controllers/HomeController.en-US.resx
Example:
@using Microsoft.AspNetCore.Mvc.Localization
There is no option for globally shared resource file but it can be achieved by using IHtmlLocalizer service.
Example:
public class MyController : Controller
{
private readonly IStringLocalizer<MyController> _localizer;
[HttpGet]
public string Get()
{
return _localizer["Title"];
}
}
Example
public class ModelClass
{
[Required(ErrorMessage = "RequiredName")]
public string Name { get; set; }
}
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.
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
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.
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
Appsettings.json
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Information"
}
},
"Console": {
"LogLevel": {
"Microsoft.AspNetCore.Mvc.Razor": "Error",
"Microsoft.AspNetCore.Mvc.Razor.Razor": "Error",
"Default": "Information"
}
},
"LogLevel": {
"Default": "Debug"
}
}
}
The same thing can be achieved using the C# code using the AddFilter method.
logging.AddFilter<Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider>("System",
Page
LogLevel.Information);
logging.AddFilter<Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider>("Microsoft.AspNe
tCore.Mvc.Razor", LogLevel.Error);
logging.AddFilter<Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider>("Microsoft.AspNe
tCore.Mvc.Razor.Razor", LogLevel.Error);
logging.AddFilter<Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider>("System",
LogLevel.Information);
...
...
})
.UseStartup<Startup>();
In controller Action
public IActionResult TestMethod()
{
using (_logger.BeginScope("Log Scope Start"))
{
_logger.LogInformation("Example Scope");
_logger.LogWarning("My Scope");
}
return View();
}
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.
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();
}
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
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();
}
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
<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.
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)
{
}
}
}
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
}
}
}
• 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.
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
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).
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
Example:
Page
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.
{
...
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.
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
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
}
}
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
{
int expected = 1;
Page
int actual = 1;
Assert.AreEqual(expected, actual);
}
We can also run the test from test explore or from individual test method from the code reference.
[DataTestMethod]
[DataRow(1,"Test")]
[DataRow(2, "Test 1")]
public void TestMethod2(int Id, string name)
{
//do something
}
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.
}
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.
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
In Program class (entry point of the project), the template code calls WebHost.CreateDefaultBuilder method that
calls UseKestrel method to use Kestrel server.
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
Page
.UseKestrel(options =>
{
//set properties of Kestrel server
});
}
• 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();
}
We can also handle service start / stop event for windows service.
62
Page
References
63
Page