Advanced Level .NET Core interview questions and answers
What is IWebHost interface in ASP.NET Core?
IWebHost is one of the building block of ASP.NETCore , It contains application configuration and kestrel server.
What is WebServer used in ASP.NET Core?
By default ASP.NETCore using Kestrel webserver.
What is ASP.NET Core application life cycle?
All clients requests goes to web server (IIS/Apache/Ngix etc), from web server to ASP.NET Core Server that is either Kestrel or other , From here to application middle ware, Here requests are handled and response generated , this response transferred to client vice versa to request.
What is HttpContext object in ASP.NET Core?
HttpContext object created by ASP.NET Core webserver , Its contains the information about request specific services , configuration details, data loads and errors information and it is passes to entire application.
What is middleware pipeline in ASP.NETCore?.
In ASP.NetCore middleware is C#.Net class handle HTTP request or response.
It is responsible to transfer request or response to the set of components that is execute in a sequence order.
In Startup class Cofigure method is used to define middleware.
In middleware components order is important , In given order only components execution will be done.
Middleware able to call another and this middleware calls another middleware and so on. This is called pipeline.
What is ViewModel?
ViewModel is a simple object contains the data required by the view to render in UI.
What is difference between Httphandler , Httpmodules and ASP.NET Core Middleware?
Httphandler process the request and send response back to browser.
Httpmodules handle the requests based events, but should have complete understanding on request state.
.NET Core middleware pipeline request transferred between different middlewares generate response. Pipeline is define in code so that we have control over request transition. you can change order whenever you want.
What is wwwroot folder in ASP.NETCore?
Image files placed and loaded from wwwroot folder.
Why ExceptionHandler middleware place in the first in ASP.NETCore?
-ASP.NETCore middleware pipeline is always bidirectional.
-Request first enter into the ExceptionHandler middleware, While entering it is almost ignored , but while sending the response it is the last middleware so that If response contains any errors, modify the response and send a friendly message back to the client or reexecute pipeline again.
-If ExceptionHandler not handling the errors webserver returns a statuscodes to the user.
What is the difference between Program class and Startup class?
-Program class is used to define required infrastructure to an application like Application settings , Logging and Web Server related etc..
-Program class required changes rarely.
-Startup class is used to define application components and features etc.
-Startup class required changes frequently.
What is ConfigureServices and Configure methods in Startup class in ASP.NET Core?
-ConfigureServices method is used to registering the service with IServiceCollection
-Configure method is used to configure the middleware pipeline for handling HTTP requests.
Services those are configured in ConfigureServices methods those are available to Configure method.
public class Startup
{
Public void ConfigureServices(IServiceCollection service)
{
//here registering the service with IServiceCollection.
}
Public void Configure(IApplicationBuilder ap)
{
//here configure the middleware pipeline for handling HTTP requests.
}
}
What is the error handling namespaces in ASP.NETCore?
Microsoft.AspNetCore.All
Microsoft.AspNetCore.Diagnostics
What is the app.UseDeveloperExceptionPage() middleware in ASP.NETCore?
-If we want to get full information about exceptions(Line number + Exception information+request that caused + Fullstack trace) while developing the application you can use this middleware.
-This middleware using DeveloperExceptionPageMiddleware class.
What is the app.UseStatusCodePages() middleware in ASP.NETCore?.
Using this middleware you can get different response for different statuscodes.
15)When do we need to return Status code as a response?
If you are building API for SPA or other application, if something went wrong in API side returning HTML response is not good so that returning status codes to client.
How can we disable middleware in ASP.NETCore?
Using HttpContext class Features property.
Example:
Public void SCode()
{
var sCodeFeature = HttpContext.Features<IStatusCodePagesFeatures>();
if(sCodeFeature != null)
{
sCodeFeature.Enabled = false;
}
}
How to add middleware in ASP.NET Core applications?
In two ways we are adding this
1)Using nuget package manager.
2)By editing project file.
Where we define Route in ASP.NETCore?
Define route in Startup class configure method.
How Cache busting handled in ASP.NETCore?
- Using app-append-version = 'true' attribute you can handle cache busting in ASP.NETCore.
- app-append-version attribute generate a unique hashcode will be generated for the server side resources , If resource got changed new hash code will be generated so that query string also getting changed
-Depends on hashcode browser handle the requests and responses.
-You can apply this attribute to <script><img><link>
What is Ok() helper method in ASP.NETCore?
-Ok helper method return 200 statuscode.
-This statuscode return when requested data found.
-If you want you can return the data,
What is NotFound() helper method in ASP.NETCore?
-NotFound helper method return 404 status code.
-This statuscode return when requested data not found.
What is BadRequest() helper method in ASP.NETCore?
-BadRequest helper method return 400 statuscode.
-This statuscode return when data provided in the request failed the validation.
Can we apply Conventional and Attribute routing on one application?
-Yes we can apply
-But always attribute routing bypass conventional routing.
Do we call single action method for multiple URL's in ASP.NETCore?
-Yes, you can call by applying multiple route attributes in single action method.
Example:
[Route("students/cse")]
[Route("students/it")]
public IActionResult GetDetails()
{
}
above action method GetDetails called for bot "students/cse" ,"students/it" routes
Why attribute routing best fit for ASP.NETCore WebAPI?
-Conventional routing defined in Stratup.cs file.
-Conventional routing evaluation always following order top to down, if first route matching control goes to that controller action method. If order is missing application will give unexpected results
-Due to above approach always specify more specific routes in first and general routes at last.
-Many Web API application has multiple endpoints , If we define routing in conventional manner there may be chance for URL conflicts, , needs to do lots of work on ordering the routes. so that attribute routing is best fit for API.
How to add global prefix to attribute routing in ASP.NETCore?
By applying route attribute to base class of controller
[Route("api")]
public class BaseController : Controller
{
}
[Route("dept")]
public class ChildController : BaseController
{
[Route("cse")]
public IActionResult GetDetails()
{
//method def
}
}
api prefixing to the URL - api/dept/cse
What is Dependency Injection, What is the use of it?
-Dependency Injection is design pattern help us to develop loosely coupled code.
-Loosely coupled components need not know much details about the components to use it.
What is dependency graph ?
-Dependency Graph is the collection of objects that must be created in ordered to request root object.
What is the DI Container (or ) IOC container in ASP.NET Core?
-DI container responsible creation of an instance of service.
-This container knows how to create an instance including all its dependencies and passing these to constructor.
How many ways inject the dependency?
1)Using constructor
2)Using Property
Using constructor is re commanded , ASP.NETCore by default supporting constrctor level
Do we have default constructor for controller class in MVC?
-Yes ,by default it is not showing but if you want can place it.
-It is automatically called by runtime when it is executing an action method.
How do we inject service into an action method in ASP.NETCore?
-By using [FromServices] attribute inject the service in action method.
-During the model binding mvc middleware can resolve the parameter from the DI container.
public IActionResult SignInStudent([FromServices]ISignServ signser,string username,string pwd)
{
signser.CheckUser(username,pwd);
return view()
}
How do we inject service in view with ASP.NETCore?
-By using @inject directive
@inject UIGenerator UG
UIGenerator - service name
UG - Alias name of the service
<h1> UG.Title</h1>
How many ways set the lifetime of instance in ASP.NETCore?
- Using 3 ways
1)Transient
2)Scoped
3)Singleton
Transient: For every service request new instance created.
services.AddTransient<DataContext>( );
Scoped: Depends on scope , For every service request new instance created. For different scopes different instances created.
services.AddScoped<DataContext>( );
Singleton: For all requests one instance created and used.
services.AddSingleton<DataContext>( );
What are the things needs to be take care while working with singleton in ASP.NETCore?
-First thing is to service instance is thread safe because it is sharing between multiple threads.
-When object creation is expensive and object not holding any states.
What are the things needs to be take care while configuring lifetime of a service in ASP.NETCore?
-A service always use dependent services which are having the lifetime longer or equal to the service
For Example:
-If service registered as a singleton service dependent service should be only singleton
-If service registered as a scoped service dependent service should be scoped or singleton
-If service registered as a transient service dependent service should be anything.
What is the meaning of configuration?
Configuration is a collection of external parameters that controls the application functionality in someway.
What is the method using for configuring ASP.NETCore application?
-using CreateDefaultBuilder( args)
What is the main components in ASP.NETCore configuration?
-Two main components
1) ConfigurationBuilder
2) IConfigurationRoot
ConfigurationBuilder : Describe the components final configuration of application
IConfigurationRoot : Contain configuration values.
Steps of configuration :
Step 1: Create an instance for ConfigurationBuilder
Step 2: Add providers to builder so that provider loads the data from different data sources.
Step 3: Call Build() , Configuration manager loads values from provider stores it IConfigurationRoot , Which represent the configuration object so that can use this in Configure( ) or ConfigurService( ) methods.
What are the different configurations providers available in ASP.NETCore?
- appsettings.json
- EnvironmentVariables
- AzureKeyVault
- AzureAppConfiguration
- CommandLineArguements
- DirectoryFiles
- In-Memory .NET objects
- CustomProviders
-In case of having multiple provides IConfigurationRoot includes values from all providers
-While configuration providers order is very important , If we have duplicate keys in providers latest one override earlier one.
What type of classes are eligible for binding in ASP.NETCore?
-Abstract classes not eligible
-Class should have public default constructor
What is TagHelpers in ASP.NETCore ?
-Using TagHelpers able to render server side code in HTML elements in Razor files.
-Diffrent kind of TagHelpers available for different purposes.
Example:
Anchor TagHelper , Environment TagHelper Etc.
<label asp-for="College.DeptName"></label>
What does it mean of self closing HTML elements?
closing also part same element is know as self closing elements.
<email mail-to="ShivaGummadidala@a.com" />
What is FormTagHelper in ASP.NETCore?
-FormTagHelper used to generate action attribute depends given data.
-By default predominately generating hidden field for preventing CSRF attacks.
CSRF token name is like "_RequestVerificationToken"
<form asp-action="GetTransport" asp-controller="GetData" asp-route-rno="5">
For above syntax generating action attribute like GetData/GetTransport/5
What is Cache busting?
-Caching is mechanism used to increase performance an application.
-With caching , all browsers cache files locally and reuse them for subsequent requests
-Caching good idea , If an application has static content and not changed frequently, in case application has frequent changes then it will create an issue.
"Cache busting solve the browser caching issue if your application has frequent changes"
-To avoid above issue appending parameter in URL like ?v=1 , browser caching the based on URL, If application changes needs to query parameter ?v=2 again changing parameter for every change in application needs to manual intervention and time taking processes.
What is the use of options pattern in ASP.NETCore?
-Using this pattern bind the collection of configuration values to strongly typed object.
-For this binding process ASP.NETCore uses the IOptions<T> interaface
Public class StudentController : Controller
{
public StudentController(IOptions<StudentDetails> options)
{
// From the options will get class information
}
}
What is the IOptions<T> in ASP.NETCore?
-IOptions<T> create an instance when it is first needed , reuse the same configuration
What is the IOptionsSnapshot<T> in ASP.NETCore?
-IOptionsSnapshot<T> create an instance when it is needed , It always contains the configuration when it was last created.
What is SQL injection attacks, How can we prevent this attacks?
-Mostly getting this attacks because of writing SQL statements manually.
-To avoid this needs to use parameterized queries.
public List<Student> GetData(string sno)
{
return context.Students.FromSql("select * from students"+"where sno= '"+sno+"'").ToLsit();
}
Form the above method , if user pass following query as a sno (studentnumber) then it is deleting students table
select * from students where sno=' '; Drop table students;
to avoid issue query should be below like this
public List<Student> GetData(string sno)
{
return context.Students.FromSql("select * from students where sno= '{0}'",sno).ToLsit();
}
How many ways will do migrations in ASP.NET?
-By using .Net CLI
-By using vspowershell cmdlets
-By calling Migrate() method in code on context class.
context.Database.Migrate( )
What is filters in ASP.NETCore MVC?
-Filter is a piece of code, used for filtering the requests and responses.
-Filters will execute before request processed or response transferred.
-If something goes wrong filters stops application execution sending response to the users.
-Some of the filters executing twice first time for request and second time for response
How many types of filters available in ASP.NETCore MVC?
in ASP.NETCore 5 types of filters available
1)Authorization Filters
2)Resource Filters
3)Action Filters
4)Exception Filters
5)Result Filters
Resource , Action and Result filters executed twice depends on usage
How can we implement filters in ASP.NETCore MVC?
-Using classes for implementing the filters in MVC
-Always use this filters as C# attributes
-Needs to decorate this attributes to controllers and action methods
How many ways to applying filters in ASP.NETCore MVC?
Applying filters in three levels
1)Action method level
2)Controller Level
3)Globally at application level
Use of applying filters at action method level with an example in ASP.NET Core MVC?
user able to access the application , if tried to access the protected action method then it will ask for login
public class StudentController : Controller
{
[LogDetailsFilter]
public IActionResult Index()
{
return view( );
}
}
Use of applying filters at controller level with an example in ASP.NET Core MVC?
user able to access the application , if tried to access the protected controller action method then it will ask for login.
-user able to access the action methods from other controllers.
[LogDetailsFilter]
public class StudentController : Controller
{
public IActionResult Index()
{
return view( );
}
}
Use of applying filters at globally at application level with an example in ASP.NET Core MVC ?
-User needs to login first then only able to access controller action methods
-For this , filters directly added to MVC services
public class Startup
{
Public void ConfigureServices(IServiceCollection service)
{
services.AddMvc(options => options.Filters.Add(new LogDetailsFilter()));
}
}
What is the filters execution order in ASP.NETCore MVC?
-Global fitters first priority , Controller scoped filters run second priority and action method level filters third priority.
-If filters applied to both base class and derived class, derived class filters execution first later base class filters.
-Resource , Action and Result filters have both execution and executed methods, Executing method will evaluates before action method execution , Executed method evaluate after action method execution. This methods execution depends on action methods execution i.e either GET or POST etc.
-For all requests execution order is Global->Controller -> Action method level , For response it is vice-versa.
Can we change filters execution order in ASP.NETCore MVC?
Yes we can change using Order property of IOrderedFilter
[FilerName(order=1)]
What is the use of ResourceFilters in ASP.NETCore MVC?
-If you want to check (or) perform an action before modal binding you can use ResourceFilters.
How to return result from filters in ASP.NETCore MVC?
-Using context.Result
What is context.cancelled = true with filters in ASP.NETCore MVC?
context.cancelled = true indicating pipeline was cancelled. Its not halting other filters execution.
How can we implement DI in your custom filters with ASP.NETCore MVC?
Using ServiceFiltersAttribute , TypeFIlterAttribute
-With ServiceFiltersAttribute needs to register filters and its dependcies with DI container.
-With TypeFIlterAttribute needs register filter dependencies
What is the difference between and middleware and filters in ASP.NETCore ?
-Middleware application specific , Filters MVC specific
-Middleware is more generalized, Filters are more specific
-Middleware runs for all requests in an application , Filters only run for MVC middleware that to depends
-Restriction on middleware is not possible , Restrictions on filters is possible.
Firsttime user authentication request life cycle in ASP.NetCore?
-user enter the credentials and click on login post them to the server
-Frist user property set to anonymous user principal
-Action method calls the signInManager , This loads the user from databse and validates
-If the password is correct, The user signed in , The user property set to the authenticated user principal
-Finally the user principal is serialized and returned as an encrypted cookie to the browser
Secondtime user authentication request life cycle in ASP.NetCore?
-Authenticated user make request
-The browser sends authenticated cookie
-Any middleware before the authentication middleware treat request as unauthenticated
-Authentication middleware calls the authentication services , it deserialize the user principle from cookie and confirms it is valid
-The HttpContext.User property is set to the deserialized principle , and the request is now authenicated
-All the middlewares after authenticated middleware see the request as from the authenticated user
What is Claim in ASP.NETCore?
Claim is single piece of information in the form of type and value both are sting type , value is optional
Example: RollNo ="123" is claim
RollNo is type
"123" is value
What is Principle in ASP.NETCore?
Principle is user of your app
For example If you app is related student info then student is principle
What is ClaimsPrinciple in ASP.NETCore?
Always principle is implemented ClaimsPrinciple
it is collection of claims
What happen if unauthenticated user trying to access an action method protected with [Authorize] attribute?
user unauthenticated is redirected to login page
if user authenticated , checking weather user has privileges to access the requested resource
What is [AllowAnonymous] attribute in ASP.NETCore MVC?
When [Authorize] attribute applied to controller level or global level and you want by pass this [Authorize] attribute to an action method then we can use this [AllowAnonymous] attribute
What happens if we apply [Authorize] attribute at Global level in ASP.NETCore MVC?
For action method access it will go to authentication so that it will go infinite loop. To avoid this situation we should use [AllowAnonymous] attribute to Login , Errorpage and Passwordreset action methods
What is ChallengeResult in ASP.NETCore ?
User not authenticated to execute an action method then will return this result
What is ForbidResult in ASP.NETCore ?
User is authenticated but not authorized to execute action method then will return this result.
When will get 401 , 403 statuscodes as response in ASP.NETCore?
401 - for un authenticated related requests
403 - for fobidden errors related requests
How to apply policies using using [Authorize] attribute in ASP.NETCore MVC?
[Authorize("Departemnt")]
public IActionResult GetDetails( )
{
return view();
}
The user who satisfy "Department" policy he can execute GetDetails action method.
How to add policy and perform Authorziation in ASP.NETCore MVC?
public void ConfigurationServices(IServiceCollection services)
{
services.AddAuthorization(options =>
options.AddPolicy("Department" , PolicyBuilder=>PolicyBuilder.RequireClaim("Designatio","HOD"));
)
}
Can we apply authorize attribute multiple time to an action method in ASP.NETCore ?
yes we can apply while applying multiple policies to same action method
[Authorize("Policy1") , Authorize("Policy2")]
-> if user satisfied above two policies then only action method can execute
Do we have an interfaces with empty methods, then what is the use?
-yes we have ,IAuthorizationRequirement interface etc
-If class is created with this interface means its represents requirement
-we call this interfaces as marker interfaces
What is bundling in ASP.NETCore MVC?
Bundling is the process of creating a single file from multiple files concatenation to reduce the number of requests
What is minification in ASP.NETCore MVC?
Minification is used to reduce the size of the file with out changing the functionality.
It is achieved by removing unused code and variables , Renaming the if possible by giving by giving short names.
What is the use of structured logging ?
-Structured logging allowing us to searching and filtering very easy on log.
-For structure logging use placeholders, parameters and category of log etc
What is [RequireHttps] in ASP.NET Core MVC?
-using this we redirect request to use HTTPS rather than http for an action method
What is [ValidateAntiForgeryToken] in ASP.NET Core MVC?
-using this attribute we validate antiforgery token to an action method or controller or golbal based on given scope
What is [AutoValidateAntiForgeryToken] in ASP.NET Core MVC?
-For GET methods most of the time need not validate anything because there no data modification
-For Validating POST , DELETE methods we used this attribute , If you apply this attribute globally its automatically ignore GET requests and onlyt validating POST , DELETE requests
What is [IgnoreAntiForgeryToken] in ASP.NET Core MVC?
-If antiforegry token applied to globally and you omit this token for some of the action methods then you can use IgnoreAntiForgeryToken attribute
How to enable CORS in ASP.NETCore ?
Globally adding by middleware
services.AddCors();
Controller or action method level by adding attribute [EnableCors]
What is Url.IsLocalUrl( ) in ASP.NETCore MVC?
-Most of the times we use this method to avoid redirecting attacks.
-Using this method you can check you can check weather URL belongs to this app or not
if(Url.IsLocalUrl( strSomeUrl))
{
return Redirect(strSomeUrl);
}
esle
{
return RedirectToAction("Index", "Home");
}
LocalRedirect( ) also working like same
What is XSS, How can we prevent this attacks?
-Cross Site Scripting attacks involves malicious user injecting content into our app to run malicious code when user browse your app.
-Using Html.Raw( ) method we can avoid this.
What is CSRF, How can we prevent this attacks?
-Cross Site Request Forgery attacks that are cookie based authentication related.
-Using antiforgerytoken we avoid this attacks 91)What is insecure object reference attacks, How can we prevent this?
-Exposing the product id (or ) id's in the URL some time leads to attacks.
-To avoid this attacks , before performing requested action needs to check weather requested user has permissions or not.
What is View components in ASP.NETCore MVC?
-View components are similar like partial views the difference is view components contains business logic and database access.
What is Run( ) extension method in ASP.NETCore?
-Using Run( ) extension method to create a middleware components that always return a reponse.
-Place Run( ) extension method always last because after Run( ) method nothing will execute in pipeline.
What is Map( ) extension method in ASP.NETCore?
Map( ) extension method is used to create a branches in the middleware , based on incoming requesting matching condition next subsequent middleware going to execute in pipeline.
What is Use( ) extension method?
Use( ) extension method is used to create generalized middleware that can be generate response modify request.
What is Areas in ASP.NET Core MVC?
-Areas are different parts of large ASP.NET Core MVC application. Every part contain smaller functionality and every area contains their own views , controllers and models.
What is migrations in ASP.NET Core?
-Migrations is mechanism provided by ASP.NETCore.
-Its used for database schema management based on data model changes
-It is provide a record over DB schema changes
-By applying migrations create a database in case not exist, if exist update the DB with EFCore data model.
Post a Comment