Showing posts sorted by relevance for query Gmail. Sort by date Show all posts
Showing posts sorted by relevance for query Gmail. Sort by date Show all posts

How To Add Signature in Gmail.

Gmail is now the most popular emails providers for many small and large businesses and for personal usage. It provides us many useful features that most Gmail users hardly use such as Gmail's Signature feature. Yes, you heard it right our favorite Gmail provides us an option to add our signature to every email we send. 


In this blog post, we are going to learn how we can automatically add our signature to every email we send or reply from Gmail.

Why do we need a Gmail Signature?

Adding a signature to any email adds recognization and authentication because it contains information about you or your company. The signature can contain details like your name your profession or the company name in which you are working or it can contain details of your social media links.


Steps to Add a Signature in Gmail.

Open your Gmail Account and click on the Settings icon in the top right corner and then click on "See all settings". 

Gmail Settings

Under General settings scroll the page a little down and search for the "Signature" option and click on "Create new".

Signature option in Gmail

You will get one popup inbox to give a name to your signature. Fill in any name of your own choice and click on "Create".

Naming Gmail Signature

Add your Gmail signature inside the given box and you can also use other given features to customize your signature by adding images and social media links.


You can check your signature default option just below create a new button and from the drop-down, you can select the name of your signature. There you will notice one checkbox "Insert signature before quoted text in replies and remove the "--" line that precedes it" check this box to add your signature to all your replies.

Adding Gmail Signature to all Emails

Now, whenever you will try to send any email your default signature will get added and if you want to remove the signature for any particular email then you can choose the quick option "Manage signature" and choose the "No signature" option from the drop-down.

Removing Default Gmail Signature

I hope you have learned the complete process of adding your signature to your Gmail but if you still face any difficulties please them in the comment section below and please do share this post if you really found this useful.

(getButton) #text=(How To Send a Confidential Email in Gmail) #icon=(link) #color=(#2339bd)

How To Use Google Services Without A Gmail Address.


Use Google service without a gmail address
Use Google Without Gmail

“One an account is all you need,” says Google, “one free account gets you into everything Google”. You may infer from this Lord of the Rings-style mantra that Google is referring to a Gmail account, which will tie you into its privacy-guzzling ecosystem for all eternity. However, it’s perfectly possible to use most Google tools without Gmail- and not just Search, YouTube, Maps and other public open sites, but those that require signing in, such as Drive, Docs and Photos.

How To Stick With Your Current Email Address.

To register for a Gmail-free Google experience-

Go to its Sign Up Without Gmail page and enter your name (or pseudonym, if you like) and email address which can be a fake one from a temporary service, provided Google allows it and it lets you receive Google’s confirmation email.

Create Google Account Without Gmail
Create a Google Account Without Gmail

Be sure not to click the ‘I would like a new Gmail address’ option- if you do, choose ‘I prefer to use my current email address’ to switch back.
You’ll also, need to enter your date of birth and gender (again, these can be fake), and provide your mobile number so Google can send you a verification code (this is harder to fake!).

Delete Your Google Account Forever
Delete Google Account

The chances are that you already have a Google account with an associated Gmail address, but if you feel like starting afresh, you can either delete it at myaccount.google.com/deleteaccount or just ditch your Gmail account at myaccount.google.com/deleteservices.

Using Android Without a Gmail Account.

Contrary to popular belief, it’s possible to use an Android phone or tablet without a Gmail address, to stop Google spying on your mobile activities. However, this will prevent you from accessing the Google Play Store and Android’s backup and syncing tools.

When you set up your device, tap Skip when you’re prompted to sign in to Gmail, then Skip again to confirm that you want to use Android without a Google account. 

Use Android Without Gmail

A couple of screens later, you’ll be asked to opt into some extra Google services, but you can decline these and tap Agree to continue. 

Built-in Google apps including Maps, Chrome, and YouTube will still work, as will the Contacts app, but be prepared for constant nags to sign into Google! 

Also read:

How To Send a Confidential Email in Gmail.

send confidential email in gmail

Every day we send and receive many emails and most of us use Gmail (Google Email) for sending our emails. Many times you send some important and confidential details through email and thinking to have a passcode on it but how many of you know that Gmail actually has this feature of sending a confidential email.

What Is The Benefit of a Confidential Email?

You can send a message or attachment with Gmail confidential mode which helps you to protect your sensitive information from unauthorized access. You can also set an expiry date for the email or remove the access at any time you want. The receiver of a confidential email cannot download, copy, print or forward that email.


But one thing you must keep in mind that the receiver can take a screenshot or photos of your confidential email.   

How Confidential Email Work.

You can also send confidential email in two different modes “No SMS Passcode” and “SMS Passcode”. 
In No SMS Passcode, the receiver does not need any passcode to read the email but in SMS Passcode, the receiver has to feed the OTP which the receiver gets on his/her mobile number set by the email sender.


How To Send Confidential Email in Gmail.

Here are the following steps to do so-

Step 1: Open your Gmail account of your PC browser and click on Compose.

compose a confidential email

Step 2: Compose the email which you want to send and click on Turn on confidential mode.

send a confidential email in gmail

Step 3: Set an expiry date for the email. After the completion of expire date, the email gets vanish from the receiver Gmail inbox.

set expiry date confidential email

Step 4: Choose any one Passcode mode-
  • No SMS Passcode- Recipient well able to open it directly.
  • SMS Passcode- Enter recipient proper phone number (not your  phone number) because recipient have to feed an OTP from the given number to read the email.
set passcode for confidential email


Step 5: Click on Save.
Step 6: Enter the recipient phone number and click on Send. 

recipient mobile number for confirm code


The recipient will get a confidential email like this (shown in the picture below) and have to verify identity.

open confideential email

You can also remove the access of the confidential email at any time you want even before the expiry date. To do so-

O1. Open your Gmail.
02. Click on Sent on the left side.
03. Open the confidential email section.
04. Click on Remove access.

Conclusion

The recipient of the confidential email cannot download, copy, forward or print the confidential email but one can take a screenshot or photo of that email.

Google rolls out new Gmail Search Filters making it easier to search your emails.

Gmail Search Filter

Gmail rolls out new updates adding a search filter for allowing users to narrow down the search results and help them to find a specific email more quickly. The new search filter for Gmail which Google calls “search chips” will appear just below the search box when you search for a particular keyword.

The new “search chips” feature for Gmail has many filter options to choose from, like ‘has attachment’, ‘To me, ‘Advanced search’, and many more. 

Here are the Gmail search chips filter options and their uses:

Any time: This filter option help you deciding how older the email in which you are searching now. There are options to choose from like older than a week, older than a month, older than 6 months, or older than one year.

Has attachment: This filter option helps you to separate those email which has some attachment files like spreadsheet or PDF in it. Earlier this feature was present accessible through Advanced search options in Gmail.   

Is Unread: This feature as the name suggests marks those emails which you haven’t read yet.
 
Gmail search chips
Gmail Search Chips

The filters options can be used in combination to narrow down the searches like if you know how older the email is and having some attachment files in it then you can use the ‘Any time’ and ‘Has attachment’ filter options to get the search result more quickly.

As Google acknowledges that, “we’ve heard from our users that searching in Gmail could be faster and more intuitive”. When the company first announced this “search chips” feature, there was no clarity about it would roll out for non-G Suite customers, but now the feature is live and available for all.

How To Log people out of your Google account.

Log people out of your Google account.

If you’re worried that someone might be reading your email – be it your spouse, your boss or the government – Gmail can reassure you and let you log out remotely. 

In your browser, scroll to the bottom of the Gmail page and click the tiny Details the link below ‘Last account activity’ in the bottom-right corner. This tells you if your account is open in another location and displays a list of recent activity, including the access type (such as browser or mobile) and IP address. 


Click the ‘Sign out of all other sessions’ button to log out from all other locations apart from your current one. Because your Gmail address is now used across all Google services, clicking this button will also sign you out of Search, Drive and more. 


On YouTube, click the cog icon in the top-right corner, select ‘YouTube settings’ and click the Advanced link below your name and email address. Click ‘Sign out of all YouTube sessions’ to stop anyone using your account.

How To Delete Your Google Account Permanently?

If you use multiple Google Accounts then there might be a chance that you have a few Google Accounts that you are not using anymore but still, exists. Google gives you the option to delete your Account and d permanently and if you want you can also save your existing data stored in different services of Google like Gmail, Google Drive, YouTube, Google Maps, etc.

Follow the steps given below to Delete your Google Account:

  • Open your Google Account in your browser. 
  • Click on Data & Privacy option from the left panel and scroll down on that page to move to the More Options section.
Google Account
  • You see the option to Delete your Google Account, click on it and it will redirect you to the next page. 
  • Google will give you the option to Download all your data related to that Google Account. Click on Download your data to choose that option.
Option to Delete Google Account


  • Scroll completely down to acknowledge and check both the check-box and finally click on Delete Account.
Deleting Google Account Forever
  • You will see one last message from Google saying "Your Google Account and all its data have been deleted". You will also get one last chance to recover your account if you change your mind at the last moment. 
Message after Deleting Google Account

So this is the complete process of deleting your Google Account permanently forever. But make sure to check your Gmail Account and Google Drive first before deleting the Account for downloading all required data. 

Google Unveils Gemini Ultra: Rebranding Existing Chatbot Bard.

Gemini Google Most Capable AI Model

In a long-anticipated move, Google has officially launched Gemini Ultra, a revolutionary version that powers Gemini Advanced. This new iteration promises an enriched user experience, excelling in reasoning, instructional guidance, coding support, and collaborative creativity. Simultaneously, Google announced the rebranding of Bard to simply "Gemini," signaling a comprehensive upgrade in its AI offerings.

Gemini Advanced transcends traditional AI capabilities, positioning itself as a personalized tutor capable of generating custom step-by-step instructions, sample quizzes, and engaging in dynamic discussions tailored to individual learning preferences. For coding enthusiasts, the chatbot becomes an invaluable companion, adept at handling advanced coding scenarios, providing ideation support, and assisting in the evaluation of different coding approaches.

How to Access Google Gemini? 

To access Gemini Advanced, users can subscribe to the Google One AI Premium Plan, priced at $19.99 per month, featuring a complimentary two-month trial. This plan not only unlocks the latest AI advancements but also includes the benefits of the existing Google One Premium plan, offering 2TB of storage.

AI Premium subscribers are set to enjoy additional perks, with upcoming access to Gemini integration in Gmail, Docs, Slides, Sheets, and more, formerly known as Duet AI. Gemini Advanced is available for users in over 150 countries and territories in English, marking a global expansion of Google's advanced AI offerings.

Mobile App for Google Gemini.

Google has introduced a dedicated mobile app for Gemini on both Android and iOS platforms. The Gemini app for Android is currently available on Google Play, initially supporting English with plans to introduce Korean and Japanese language support next week. By downloading the Gemini app or opting in through Google Assistant, users can seamlessly access the new overlay experience, whether through the app or other activation methods like the power button, corner swiping on select phones, or using the "Hey Google" command.

On iOS, the introduction of Gemini access is slated for the coming weeks within the Google app. Users can effortlessly toggle the Gemini feature, engaging in conversations to boost creativity, generate custom images, seek assistance in writing social posts, and even plan activities – all directly from the Google app.

Google's Gemini Ultra marks a significant leap forward in AI capabilities, offering a multifaceted approach to learning, coding, and creative collaboration. The integration of Gemini across platforms reflects Google's commitment to providing users with a seamless and advanced AI experience, pushing the boundaries of innovation in the digital landscape.

Different Types of Machine Learning System.

Data Mining is a process of applying ML techniques to dig into large amounts of data can help to discover patterns that were not immediately apparent.


Types of Machine Learning System:

Machine Learning system can be classified according to the amount and type of supervision they get during training.


Supervised learning: In supervised learning, the training data you feed to the algorithm includes the desired solutions, called labels.

supervised learning

Spam Filter of your Gmail Inbox is a good example of this, as it is trained with many emails (spam & ham) and it must have to learn how to classify new emails.

A typical supervised learning task is classification.


Some important supervised learning algorithm:

  • K-Nearest Neighbors.
  • Linear Regression.
  • Logistic Regression.
  • Support Vector Machines(SVMs).
  • Decision Trees.
  • Random Forest.
  • Neural network.

Unsupervised Learning: In unsupervised learning, the training data unlabeled and the system try to learn without the teacher.


Some important unsupervised learning algorithm:

  • Clustering.
  • K-Means.
  • Hierarchical Cluster Analysis(HCA).
  • Expectation-Maximization.
  • Visualization and dimensionality reduction.
  • Principal component analysis(PCA).
  • Kernel PCA.
  • Logical Linear Embedding(LLE)
  • t-distributed Stochastic Neighbor Embedding(t-SNE).
  • Association rule learning.
  • Apriori.
  • Eclat.
unsupervised learning

For example Grouping the visitor of your blog into a different group like 40% of visitors are male who likes cricket and 20% of men like football. You don’t even have to tell which group visitors belongs to, the clustering algorithm finds those connections by themselves.

 

Semisupervised Learning: In this, the algorithm has to deal with lots of unlabeled data and a little bit of labeled data.


Google Photos are good examples of semisupervised learning. After uploading the photos, it automatically recognize if a person is present in many different photos now you just have to tell who these people are. One label per person and later it will help you search for photos.  


Most of the semisupervised learning algorithms are a combination of supervised and unsupervised algorithms.


Reinforcement Learning: The best example of a reinforcement learning algorithm is a robot learning how to walk. The robot observes the environment, select and perform an action and get rewards or penalties, and base on this the robot decide what to do and what not to do.  

reinforcement learning

Another criterion used to classify Machine Learning systems is whether or not the system can learn incrementally from a stream of incoming data.


Batch Learning: In batch learning, the system is not capable of learning incrementally with time. As it takes a lot of time and computing resources so the entire process is done offline. First, the system is trained, and then it is launched into production and runs without learning anymore. It is also known as offline learning.


Online Learning: In this algorithm, you train the system incrementally by feeding data continuously, either individually or by small groups called mini-batches. The best use of this learning is for stock prices where data change rapidly.


Machine Learning system is also categorized base on generalization:


Instance-based learning: In this learning, the system learns the old examples by heart then generalizes to new cases using a similarity measure.


Model-based learning: In model-based learning, we build a model of these examples then use that model to make predictions.  

How To Change The Login Email Address of a Blogger (Blogspot) Account.


blogger gmail change

Changing the blogger email address or moving one blogger account to another email address is not a one-step process and blogger does not permit to it directly but still, there is a way by which you can change your email address for the blogger account.

There are many possible reasons for which you want to change the email of your blogger account.

Some Possible reasons are that-


  • Most of blogger start there blog with a random email address and later they think that the email address should match the blog niche. You want to change the email address because you want to match your email Address with the blog niche.


  • You create a blog and after running it for a few months, you got a buyer and to change the ownership of that blogger account, you want to change the email address with your buyer email address.


  • You are running multiple blogs and finding it difficult to manage all with the same email id. To manage your different blogs with different email id.

How To Transfer one Blogger Account to Another Email Address.

Before starting the process, let us consider that you want to move a blogger account from Email A to Email B.

Here are the following steps to do so-


Step1: Open your blogger account and select the blog for which you want to change the email (Email A) then go to Settings > Basic. Under Basic settings, scroll down and move to Permissions then click on +Add Authors.

logger

Step 2: Add another email Id (Email B) to which you want to move this blogger account and click on Invite authors.

blogger author

Step 3: Open the other email account (Email B) in a different browser or device. Now open the email that you got and click on Accept invitation. After clicking on Accept invitation button, you will redirect to blogger account.

blogger email change

Important note:
Perform this entire process with two different browsers, one browser login with Email A and another login with Email B. You can also use two different devices.

Step 4: Inside the blogger account, check the email shown there (should match with Email B) and click on Accept invitation button once again.

move blogger account

Now you can see that the blog is added to the blogger account in which you want to add but as an author profile and you are not getting the complete access of the blog. To get the complete access of the blog and remove the same blog from the previous email address (Email A), continue the steps shown below-

Step 5: Open the previous blogger account (Email A), go to Settings > Basic > Permissions. Select the new email address which is added there and select Admin from the drop-down menu.

blogger admin setting

Step 6: Now open another blogger account (Email B) and go to Settings> Basic> Permissions section, remove the email address (Email A) by clicking on the cross button.

admin setting

This is the complete process by which you can change the email address of a blogger account or move one blogger account to another.

Suggestion

My small suggestion is if you want to change the email address of your (Blogspot) blog then try to change it in earlier days of your blogging because once you start with a blog, your visitors getting connected with your email, your Adsense account and many more things are there and changing the email address at that time also follow the same process but may affect you a lot.

ASP.NET Core Interview Questions

Q1. What is .NET / .NET Core?

.NET is a free, open-source, cross-platform development platform from Microsoft used to build different types of applications such as Web APIs, web applications, cloud services, desktop applications, mobile applications, and background services.

.NET Core was the cross-platform, high-performance generation of .NET introduced as the successor to the .NET Framework. Starting with .NET 5, Microsoft unified the platform and dropped the "Core" name, so today we generally refer to it simply as .NET.

Q2. What is CLR, and how does it work?

CLR (Common Language Runtime) is the execution environment of .NET applications. It is responsible for running managed code and providing services such as memory management, garbage collection, exception handling, thread management, type safety, and security.

In simple terms, CLR is the runtime that takes the compiled .NET code and manages its execution. The execution flow is:

C# Source Code
      ↓
C# Compiler
      ↓
IL / CIL (Intermediate Language)
      ↓
CLR loads the assembly
      ↓
JIT Compiler
      ↓
Native Machine Code
      ↓
CPU executes

Q3. What is the difference between CLR and CTS?

CLR (Common Language Runtime) is the execution environment that runs and manages .NET applications, whereas CTS (Common Type System) is the specification that defines how data types are represented, declared, and used across .NET languages.
CLR CTS
Runtime execution environment Type system specification
Runs managed .NET code Defines rules for .NET types
Handles GC, exceptions, threading, JIT, etc. Defines types such as Int32, String, Object, classes, structs, interfaces, etc.
Responsible for execution and management Responsible for type consistency and interoperability
Works at runtime Defines the type rules followed by .NET languages

Q4. How Garbage Collection works in .Net Core?

Garbage Collection (GC) in .NET Core/modern .NET is an automatic memory-management system that identifies objects that are no longer reachable by the application and reclaims the memory they occupy. This means developers generally don't need to manually allocate and free managed memory.

The basic process of GC is:
Object Created
      ↓
Managed Heap
      ↓
Object becomes unreachable
      ↓
GC identifies it as garbage
      ↓
GC collects it
      ↓
Memory is reclaimed

Note: .NET GC uses generational garbage collection because most objects become unreachable quickly.
  • Gen 0 → Newly allocated, short-lived objects
  • Gen 1 → Objects that survived a Gen 0 collection
  • Gen 2 → Long-lived objects

Q5. What is the difference between Dispose() and Garbage Collection?

Dispose() and Garbage Collection serve different purposes. Dispose() is used by the developer to explicitly release unmanaged or external resources, while Garbage Collection automatically reclaims memory occupied by managed objects that are no longer reachable.

Dispose() Vs Garbage Collection:
Dispose() Garbage Collection
Manual/deterministic cleanup Automatic memory cleanup
Implemented through IDisposable Managed by the .NET GC
Used mainly to release unmanaged/external resources Reclaims memory of unreachable managed objects
Happens when code calls Dispose() or uses using Happens automatically when GC determines collection is needed
Timing is predictable Timing is non-deterministic
Does not directly free managed object memory Reclaims managed heap memory
We can manually request Garbage Collection in .NET using GC.Collect(), but it is generally not recommended in normal application code. The .NET GC is optimized to determine when collection is beneficial, so forcing a collection can negatively impact performance.

Q6. What is Kestrel, and what are the advantages of Kestrel in ASP.NET Core?

Kestrel is the default cross-platform web server for ASP.NET Core applications.

It is responsible for:

  • Listening for incoming HTTP/HTTPS requests
  • Accepting connections from clients
  • Processing HTTP requests
  • Passing requests into the ASP.NET Core middleware pipeline
  • Sending the HTTP response back to the client

The major advantages of the Kestrel server are high performance, lightweight architecture, cross-platform support, container and cloud friendliness, support for HTTPS, WebSockets, HTTP/2 and HTTP/3, and the ability to run standalone or behind a reverse proxy such as IIS or Nginx.

Example: A client sends an HTTP request to Kestrel. Kestrel accepts the network connection and forwards the request into the ASP.NET Core middleware pipeline. The request then reaches routing, authentication, authorization, controllers, or endpoints, and the response travels back through the middleware pipeline to Kestrel, which sends it back to the client.

Q7. What is the difference between IIS and Kestrel? Why do we need two web servers?

Kestrel is the cross-platform web server used by ASP.NET Core to handle HTTP/HTTPS requests and run the ASP.NET Core application. IIS is a Windows web server that can be used as a reverse proxy or hosting layer in front of an ASP.NET Core application.

We don't necessarily need both. Kestrel can run the application directly, which is common in containers, Linux, and cloud-native environments. In a traditional Windows enterprise environment, we may put IIS in front of Kestrel to use IIS features such as Windows integration, request filtering, logging, TLS handling, and reverse-proxy capabilities.

IIS and Kestrel have different responsibilities, and using both is an architectural choice rather than an ASP.NET Core requirement.

IIS vs Kestrel Server:

# IIS Kestrel
Platform Windows-only web server Cross-platform: Windows, Linux, macOS
Role Can act as a front-end web server / reverse proxy Primarily the HTTP server for ASP.NET Core
Hosting Can host ASP.NET Core through IIS hosting models Directly hosts ASP.NET Core applications
Architecture Often sits in front of Kestrel in traditional Windows deployments Can run standalone or behind IIS/Nginx/load balancer
Main Strength Windows integration, authentication, process management, request filtering, logging Lightweight, high-performance, cloud/container-friendly, cross-platform

IIS is very old software and comes with a considerable legacy and bloat. With Kestrel, Microsoft started with high performance in mind. They developed it from scratch, which allowed them to ignore the legacy/compatibility issues and focus on speed and efficiency.

However, Kestrel doesn’t provide all the rich functionality of a full-fledged web server such as IIS, Nginx, or Apache. Hence, we typically use it as an application server, with one of the above servers acting as a reverse proxy.

Q8. What is Generic Host or HostBuilder in .NET Core?

The Generic Host is the infrastructure that provides the lifetime, configuration, dependency injection, logging, and environment management for a .NET application.

It was introduced to provide a common hosting model not only for ASP.NET Core web applications, but also for background services, worker services, console applications, and other long-running applications.

HostBuilder is the mechanism used to configure and build this Generic Host. In modern .NET, this is usually done through Host.CreateApplicationBuilder() or WebApplication.CreateBuilder() rather than manually creating a HostBuilder.

The Generic Host brings together:

  • Dependency Injection → Registers and resolves services
  • Configuration → appsettings.json, Environment variables, command-line arguments, etc.
  • Logging → Configures application logging
  • Environment → Development, Staging, Production
  • Application Lifetime → Start, run, and graceful shutdown
  • Hosted Services → IHostedService / BackgroundService
 Example:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IOrderService, OrderService>();

var app = builder.Build();

app.MapGet("/orders", () => "Orders");

app.Run();

Here, WebApplication.CreateBuilder() sets up the host and application infrastructure, including configuration, logging, dependency injection, and hosting.

Q9. What is the purpose of the .csproj file?

The .csproj file is the project configuration file for a .NET application. It defines how the project is built, compiled, packaged, and managed.

It contains important information such as the target .NET version, NuGet package dependencies, project references, build settings, output type, and other MSBuild properties.

Example:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="..." />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="../MyLibrary/MyLibrary.csproj" />
  </ItemGroup>

</Project>
  • TargetFramework → Specifies which .NET version the application targets.
  • PackageReference → Defines NuGet dependencies.
  • ProjectReference → References another project.
  • PropertyGroup → Defines build/compiler settings.
  • SDK → Specifies the project SDK, such as Microsoft.NET.Sdk.Web.

Q10. What is the "Startup" class in ASP.NET Core before ASP.NET Core 6?

The startup class is the entry point of the ASP.NET Core application. Every ASP.NET Core (ASP.Net Core 5 and earlier) application must have this class. It contains the necessary code to bootstrap the application. This class contains two methods: Configure() and ConfigureServices().
  • Configure(): The Configure() method is used to add essential middleware(s) to the application request pipeline.
  • ConfigureServices(): The ConfigureServices() method is used to add services to the IoC container.
In Asp.Net Core 6 (.NET 6), Microsoft unifies Startup.cs and Program.cs into a single Program.cs.

In ASP.NET Core 6 (and up), we need to add everything, such as registering middleware to the application pipeline, adding services to the IoC container, configuring the application configuration, configuring the logger, authentication, and adding DbContext in the Program.cs file.

Q11. What does WebApplication.CreateBuilder() do?

WebApplication.CreateBuilder() is the modern ASP.NET Core entry point used to create and configure a web application. It initializes the application's hosting environment, configuration, logging, dependency injection, and web server defaults, and returns a WebApplicationBuilder that we use to register services and configure the application.

It essentially replaces much of the setup that previously required HostBuilder, WebHostBuilder, and the Startup class.

WebApplication.CreateBuilder()
        │
        ├── Creates Host
        ├── Loads Configuration
        ├── Configures Logging
        ├── Sets Environment
        ├── Configures Dependency Injection
        └── Configures Web Server defaults
                    │
                    ▼
             WebApplicationBuilder

Example: 
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddScoped<IOrderService, OrderService>();

var app = builder.Build();

app.UseAuthorization();
app.MapControllers();

app.Run();

Q12. What is Middleware?

Middleware is a software component in the ASP.NET Core HTTP request pipeline that handles HTTP requests and responses. Each middleware can inspect, modify, or process the request, perform some operation, and then either pass the request to the next middleware or short-circuit the pipeline and generate a response itself.

The main responsibilities of middleware:
  • Generate an HTTP response for an incoming HTTP request
  • Intercept and make changes to an incoming HTTP request and pass it on to the next piece of middleware.
  • Intercept and make changes to an outgoing HTTP response and pass it on to the next piece of middleware.

HTTP Request
     ↓
Middleware 1
     ↓
Middleware 2
     ↓
Middleware 3
     ↓
Controller / Endpoint
     ↓
Middleware 3
     ↓
Middleware 2
     ↓
Middleware 1
     ↓
HTTP Response

Middleware can be used for common cross-cutting concerns such as:

  • Authentication
  • Authorization
  • Exception handling
  • Logging
  • CORS
  • HTTPS redirection
  • Request/response modification
  • Static files
Middleware executes in the order it is added to the pipeline, and the order matters. A middleware can execute code before and after the next middleware, or short-circuit the pipeline without calling next().

You can also create Custom Middleware: A custom middleware is a class you create to implement your own request/response processing logic.

Step 1: Create the Middleware.
public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Before the next middleware
        Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");

        await _next(context);

        // After the next middleware
        Console.WriteLine($"Response: {context.Response.StatusCode}");
    }
}

Step 2: Register it in Program.cs
var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.UseMiddleware<RequestLoggingMiddleware>();

app.MapControllers();

app.Run();

The important part is:
await _next(context);
It passes the request to the next middleware. Without this, the middleware can short-circuit the pipeline.

Q13. What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run()?

Use() and Run() are both used to add middleware to the ASP.NET Core request pipeline, but the key difference is that Use() can call the next middleware, while Run() is terminal and does not have a next middleware.

Q14. What is the use of the "Map" extension while adding middleware to the ASP.NET Core pipeline?

Map() is used to create a separate branch in the ASP.NET Core middleware pipeline based on the request path. When the incoming request path matches the specified path, ASP.NET Core executes the middleware registered inside that branch instead of continuing through the main pipeline.

Example:
app.Map("/admin", adminApp =>
{
    adminApp.Run(async context =>
    {
        await context.Response.WriteAsync("Admin Area");
    });
});

app.Run(async context =>
{
    await context.Response.WriteAsync("Main Application");
});

Requests behave like:
/admin/users
     ↓
Map("/admin")
     ↓
Admin branch

Common Use Cases
  • Creating separate pipelines for different URL paths
  • Admin-specific middleware
  • API-specific middleware
  • Separating different application areas

Tip: Easy way to remember:
  • Use → Continue the pipeline
  • Run → End the pipeline
  • Map → Branch the pipeline based on the path


Q15. What is the right order of middleware used in production-level applications?

There is no single universal middleware order for every ASP.NET Core application, but middleware order is critical because each middleware runs in the order it is registered. In a typical production Web API, the pipeline commonly starts with exception handling, then HTTPS/security-related middleware, routing, CORS, authentication, authorization, and finally endpoint mapping.

ASP.NET Core Middleware Order

Q16. What is Routing?

Routing in ASP.NET Core is the mechanism that matches an incoming HTTP request to a specific endpoint, such as a controller action, Razor Page, or minimal API endpoint. It examines information like the URL path and HTTP method and determines which code should handle the request.

Example:
[ApiController]
[Route("api/products")]
public class ProductController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        return Ok();
    }
}

For this request: GET /api/products/10
  • Controller → ProductController
  • Action → GetProduct
  • id → 10

Q17. What are the different types of Routing?

All routes are registered when the application starts. There are two types of routing supported by ASP.NET Core
  1. Conventional routing
  2. Attribute routing
Conventional Routing: Conventional routing defines a common route pattern for the application, typically{controller}/{action}/{id?}, and ASP.NET Core uses that convention to map URLs to controller actions. It is commonly associated with MVC applications, while Web APIs often prefer attribute routing.

Example: 
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

If you use conventional routing, then there will be no information on the controller or action methods.
public class ProductController : Controller
{
    public IActionResult Index()
    {
        return Ok("All Products");
    }

    public IActionResult Details(int id)
    {
        return Ok($"Product {id}");
    }
}

Attribute Routing: In attribute routing, you define the route close to the controller/action using attributes, making the relationship between an endpoint and its URL explicit. It is generally preferred for REST APIs because it provides precise control over HTTP verbs and URL patterns.

Example:
[ApiController]
[Route("api/products")]
public class ProductController : ControllerBase
{
    [HttpGet]
    public IActionResult GetProducts()
    {
        return Ok("All Products");
    }

    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        return Ok($"Product {id}");
    }

    [HttpPost]
    public IActionResult CreateProduct()
    {
        return Ok("Product Created");
    }
}
Here, we don't depend on the controller/action naming convention.

Conventional Vs Attribute Routing.

Conventional Routing Attribute Routing
Route defined centrally Route defined on controller/action
It is based on conventions It is explicit
Common in MVC applications Very common in Web APIs
Less configuration on controllers More explicit controller configuration
URL often follows method/controller names URL can be completely different from the method name

Q18. What is the purpose of the wwwroot folder?

The wwwroot folder is a special folder in an ASP.NET Core web application that serves as the web root. Its purpose is to store static files, such as HTML, CSS, JavaScript, images, and other client-side assets that need to be directly accessible by the web browser.

When a web application receives a request, the web server looks for the requested resource within the wwwroot folder. If the resource is found in this folder, the web server serves it directly to the client without involving the ASP.NET Core middleware pipeline.

If we want to change the path of the wwwroot folder, then you need to set the path of the wwwroot folder in the WebRootPath property of the WebApplicationOptions class.

var builder = WebApplication.CreateBuilder(new WebApplicationOptions() {
 WebRootPath = "foldername"
});

Note: UseStaticFiles() enables ASP.NET Core to serve files from wwwroot.

Q19. What is a Controller?

A Controller in ASP.NET Core is a class that handles incoming HTTP requests, executes the required application logic through services, and returns an HTTP response to the client. It is commonly used in Web APIs and MVC applications to define application endpoints.

Example: 
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        return Ok(new
        {
            Id = id,
            Name = "Laptop"
        });
    }
}

A controller generally:
  1. Receives the HTTP request
  2. Gets input from route/query/body
  3. Calls application/business services
  4. Returns an HTTP response such as 200, 201, 400, 404, or 500
Business logic should generally not be placed directly inside the controller; controllers should remain thin and delegate work to services.
  • ControllerBase → Commonly used for Web APIs
  • Controller → Extends ControllerBase and adds MVC/View-related functionality

Q20. What is an Action Method?

An Action Method is a public method inside an ASP.NET Core Controller that handles a specific HTTP request and produces an HTTP response. Routing maps an incoming request to the appropriate action method based on the URL, HTTP method, route parameters, and other routing rules.

Example:
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        return Ok($"Product: {id}");
    }

    [HttpGet("{id}")]
    public ActionResult<Product> GetProduct(int id)
    {
        var product = GetProductFromDb(id);

        if (product == null)
            return NotFound();

        return Ok(product);
    }
}

If you observe, the return type of an action method, such as IActionResult or ActionResult<T> is completely different from any regular method. Both are used as return types for controller actions, but ActionResult<T> additionally tells the compiler and API tools what successful response type the action returns.

Q21. Explain different types of Action Results in ASP.NET Core?

Action Results are objects returned by controller actions that represent the HTTP response sent back to the client. They can represent success, failure, redirects, files, views, or other HTTP responses. 

The most important action results for interviews are:
Action Result HTTP Status Purpose Common Usage
Ok() / Ok(object) 200 Request completed successfully GET requests returning data
Created() 201 New resource was successfully created POST requests
CreatedAtAction() 201 Creates a resource and provides the URL of the created resource RESTful POST requests
NoContent() 204 Request succeeded, but there is no response body PUT, PATCH, DELETE
BadRequest() 400 Client sent an invalid request Invalid input, validation errors
Unauthorized() 401 Authentication is required, or credentials are invalid Missing/invalid access token
Forbid() 403 User is authenticated but not authorized Insufficient permissions/roles
NotFound() 404 Requested resource does not exist Resource lookup by ID
Conflict() 409 Request conflicts with the current state of the resource Duplicate record, concurrency conflict
UnprocessableEntity() 422 Request is syntactically valid but cannot be processed semantically Business validation failures
Redirect() 3xx Redirects the client to another URL URL redirection
RedirectToAction() 3xx Redirects to another controller action MVC applications
File() 200 Returns a file to the client PDF, image, Excel, download APIs
Content() 200 Returns custom text/content Plain text, custom content
Json() 200 Returns data formatted as JSON MVC/custom JSON responses
View() 200 Returns an MVC Razor view ASP.NET Core MVC applications

Q22. What’s the HttpContext object? How can you access it within a Controller?

HttpContext is an object in ASP.NET Core that represents the current HTTP request and response context. It provides access to information about the client request, HTTP response, user identity, headers, cookies, session, request services, and other information related to the current request.

In simple terms:
HttpContext
├── Request   → Information coming from client
├── Response  → Information sent to client
├── User      → Current authenticated user
├── Session   → Session data
├── Headers   → HTTP headers
├── Cookies   → Request/response cookies
└── RequestServices → Dependency Injection services

In a Controller, you can access it directly using the inherited HttpContext property:
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        var userAgent = HttpContext.Request.Headers.UserAgent;
        var user = HttpContext.User;

        return Ok();
    }
}

You can also explicitly inject IHttpContextAccessor when you need HttpContext outside a Controller, such as in a service:
public class ProductService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public ProductService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string GetUserName()
    {
        return _httpContextAccessor.HttpContext?.User?.Identity?.Name;
    }
}

Inside a Controller, HttpContext is already available through the base Controller/ControllerBase class. IHttpContextAccessor is mainly used when you need access to the current HTTP context from a class that is outside the controller, such as a service.

Q23. What is model binding in ASP.NET CORE?

Model Binding in ASP.NET Core is the process of automatically taking data from an HTTP request and converting it into .NET objects or parameters that can be used by a controller action. It saves us from manually reading values from the request, converting strings to integers, parsing JSON, etc. 

Let's understand this with an example. Suppose you have an API to create a product. So your product model class will look like this:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}

And your controller will look like this:
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateProduct(Product product)
    {
        return Ok(product);
    }
}

The client send a POST request:
POST /api/products
Content-Type: application/json

{
    "id": 101,
    "name": "Laptop",
    "price": 75000,
    "category": "Electronics"
}

ASP.NET Core automatically takes the JSON request body and creates a Product object:
HTTP Request Body
        ↓
Model Binding
        ↓
Product object
├── Id       = 101
├── Name     = "Laptop"
├── Price    = 75000
└── Category = "Electronics"
        ↓
CreateProduct(Product product)
So you don't need to manually read the request body. ASP.NET Core does the binding for you.

Q24. How does validation work in ASP.NET CORE MVC, and how they follow the DRY principle?

Validation in ASP.NET Core MVC is mainly handled through Model Validation. After model binding converts incoming request data into a .NET model, ASP.NET Core validates that model using validation rules such as Data Annotation attributes or custom validation logic. The validation errors are stored in ModelState.

This supports the DRY principle because validation rules can be defined once on the model and then automatically applied wherever that model is used, instead of writing the same validation checks inside every controller action.

Example: 
public class Product
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }

    [Range(1, 100000)]
    public decimal Price { get; set; }
}

Controller:
[HttpPost]
public IActionResult Create(Product product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // Save product
    return Ok(product);
}

Note: With [ApiController], ASP.NET Core automatically performs model-state validation and can return a 400 Bad Request response when validation fails, so you often don't need to explicitly write: if (!ModelState.IsValid)

Q25. How to create Custom Validation?

Custom validation in ASP.NET Core is used when built-in Data Annotation attributes such as [Required], [Range], or [StringLength] cannot express a business rule. We can create custom validation using ValidationAttribute, IValidatableObject, or custom model-validation mechanisms.

Example: Employee age must be 18 or above.

using System.ComponentModel.DataAnnotations;

public class MinimumAgeAttribute : ValidationAttribute
{
    private readonly int _minimumAge;

    public MinimumAgeAttribute(int minimumAge)
    {
        _minimumAge = minimumAge;
    }

    protected override ValidationResult? IsValid(
        object? value,
        ValidationContext validationContext)
    {
        if (value == null)
            return ValidationResult.Success;

        int age = Convert.ToInt32(value);

        if (age < _minimumAge)
        {
            return new ValidationResult(
                $"{validationContext.DisplayName} must be at least {_minimumAge} years old.");
        }

        return ValidationResult.Success;
    }
}

Apply it to the model:
public class Employee
{
    [Required]
    public string Name { get; set; }

    [MinimumAge(18)]
    public int Age { get; set; }
}

The response will contain a validation error similar to:
{
    "errors": {
        "Age": [
            "Age must be at least 18 years old."
        ]
    }
}

Q26. What is the MVC pattern?

MVC stands for Model-View-Controller. It is a design pattern that separates an application into three main components: Model, View, and Controller. The goal is to separate data/business logic, user interface, and request handling so the application is easier to maintain, test, and scale.
  • Model: The Model represents application data and business rules.
  • View: The View is responsible for presenting data to the user. In ASP.NET Core MVC, this is typically a Razor View (.cshtml) that generates HTML.
  • Controller: The Controller receives the HTTP request, coordinates with services/models, and decides what response should be returned.
MVC Pattern
ASP.NET Core MVC Flow
Benefits of the MVC Architectural Pattern.
  • Clean separation of concerns.
  • Each component (model, view, and controller)  performs a single responsibility.
  • Identifying and fixing errors will be easy.
  • Each component can be developed independently.
  • The view and controller depend on the model, but the model doesn't depend on either the view or the controller.
  • Unit testing of individual components is easier.
Note: For an ASP.NET Core Web API, you usually don't have a View. So when discussing MVC in an interview, distinguish between ASP.NET Core MVC applications and ASP>NET Core Web APIs.

Q27. Explain the differences between ViewData and ViewBag.

Both ViewData and ViewBag are used to pass small amounts of data from the Controller to a View in ASP.NET Core MVC. The main difference is how they access the data. ViewData uses a dictionary with string keys to access the data, while ViewBag uses property names.

Important point: ViewBag and ViewData actually share the same underlying storage.

ViewData Example:

public IActionResult Index()
{
    ViewData["Message"] = "Hello World";
    return View();
}
View: <h2>@ViewData["Message"]</h2>

ViewBag Example:
public IActionResult Index()
{
    ViewBag.Message = "Hello World";
    return View();
}
View: <h2>@ViewBag.Message</h2>

They are useful for small, temporary pieces of data such as a page title or a message. For larger or important data, a strongly typed ViewModel is generally preferred because it provides better compile-time safety and clearer contracts.

Q28. Explain strongly-typed views.

A strongly-typed view is a Razor view associated with a specific model type using @model. It provides compile-time type checking, IntelliSense, and a clear contract between the Controller and View, making it safer and more maintainable than ViewBag or ViewData.

Example: Model
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public IActionResult Details(int id)
{
    var product = new Product
    {
        Id = 101,
        Name = "Laptop",
        Price = 75000
    };

    return View(product);
}

View:
@model Product

<h2>@Model.Name</h2>
<p>Price: @Model.Price</p>
<p>Product ID: @Model.Id</p>

Note: The @model directive defines the type of model the View expects, while @Model provides access to the actual model instance passed by the Controller.

Q29. Explain the purpose and usage of layout views in ASP.NET Core?

A Layout View is a shared Razor template used to define common UI elements such as headers, navigation, footers, and scripts. Individual Views provide page-specific content through @RenderBody() and can provide additional content through @RenderSection(). This promotes reuse and follows the DRY principle.

Typical Structure:
Views/
├── Shared/
│   └── _Layout.cshtml
├── Home/
│   ├── Index.cshtml
│   └── About.cshtml

_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
    <title>My Application</title>
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>

    <header>
        <h1>My Application</h1>
        <nav>
            <a href="/">Home</a>
            <a href="/Products">Products</a>
        </nav>
    </header>

    <main>
        @RenderBody()
    </main>

    <footer>
        <p>© 2026 My Application</p>
    </footer>

</body>
</html>

Q30. Explain partial views in ASP.NET Core.

A Partial View in ASP.NET Core MVC is a reusable Razor View (.cshtml) that contains a small portion of UI that can be shared across multiple Views. It is mainly used to avoid repeating the same HTML markup and to break a large View into smaller, manageable components.

Note: A Layout controls the common structure of the entire page, whereas a Partial View is a reusable UI fragment that can be included inside a View or Layout.

Q31. Explain the difference between PartialAsync() and RenderPartialAsync().

PartialAsync() and RenderPartialAsync() are asynchronous HTML helper methods used to render partial views in ASP.NET Core MVC. The main difference is that PartialAsync() returns the rendered HTML as IHtmlContent, whereas RenderPartialAsync() writes the rendered HTML directly to the output.

Example of PartialAsync():
@model Product

<h2>Product Details</h2>

@await Html.PartialAsync("_Product", Model)
How it works:
  1. PartialAsync() renders _Product.cshtml.
  2. It returns the generated HTML as IHtmlContent.
  3. Razor writes that HTML into the page.
Example if RenderPartialAsync():
@model Product

<h2>Product Details</h2>

@{
    await Html.RenderPartialAsync("_Product", Model);
}
How it works:
  1. RenderPartialAsync() renders _Product.cshtml.
  2. It writes the generated HTML directly to the output.
  3. It returns Task, not IHtmlContent.

Q32. What are View Components?

A View Component in ASP.NET Core MVC is a reusable UI component that encapsulates both presentation logic and a Razor View. It is similar to a Partial View, but unlike a Partial View, a View Component can execute its own logic, retrieve data through services or dependency injection, and pass that data to its View.

View Components are useful for reusable UI sections such as shopping carts, navigation menus, notifications, dashboards, and product summaries.

Example: Shopping Cart View Component

1. Create the View Component
ViewComponents/CartSummaryViewComponent.cs
using Microsoft.AspNetCore.Mvc;

public class CartSummaryViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        int cartItemCount = 3;

        return View(cartItemCount);
    }
}

The class name ends with ViewComponent, and its default component name is CartSummary. 

2. Create the Component View
Create this file at: Views/Shared/Components/CartSummary/Default.cshtml
@model int

<div class="cart-summary">
    Shopping Cart: @Model items
</div>

3. Use the View Component in a Razor View
@await Component.InvokeAsync("CartSummary")

Output: Shopping Cart: 3 items

View Component vs Partial View.
Partial View View Component
Primarily reusable UI markup Reusable UI with its own presentation logic
Receives a model from the caller Can prepare its own model and retrieve data
No dedicated component logic class Has a dedicated View Component class
Suitable for simple UI fragments Suitable for dynamic, data-driven UI sections

Important Interview Points
  • A View Component is not a Controller or an HTTP endpoint.
  • It supports dependency injection, so you can inject services to retrieve data.
  • Its logic is usually defined in an Invoke() or InvokeAsync() method.
  • Its Razor view is conventionally stored in Views/Shared/Components/{ComponentName}/Default.cshtml.
Use a View Component over a Partial View when a reusable UI section requires its own presentation logic, data retrieval, or dependency injection. A Partial View is more suitable when I simply need to reuse existing HTML markup and pass a model to it.

Q33. Explain how dependency injection works in ASP.NET Core?

Dependency Injection (DI) in ASP.NET Core is a design technique used to provide a class with the dependencies it needs instead of making the class create those dependencies itself. ASP.NET Core has a built-in IoC (Inversion of Control) container that manages service registration, object creation, dependency resolution, and object lifetimes.

DI promotes loose coupling, maintainability, testability, and the SOLID principles, especially the Dependency Inversion Principle.
Dependency Injection in ASP.NET Core
Dependency Injection Workflow

How Dependency Injection Works: There are three main steps:
  1. Register the service in the DI container.
  2. Request the dependency through a class constructor.
  3. Let ASP.NET Core resolve it when creating that class.
Example use of DI in .Net Core.
// Step 1: Create an Interface
public interface IProductService
{
    string GetProduct();
}

// Step 2: Implement the interface
public class ProductService : IProductService
{
    public string GetProduct()
    {
        return "Laptop";
    }
}

Register the service in Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IProductService, ProductService>();

var app = builder.Build();

app.MapControllers();
app.Run();
Here, AddScoped() registers ProductService as the implementation of IProductService.

Inject the dependency into a controller
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet]
    public IActionResult GetProduct()
    {
        return Ok(_productService.GetProduct());
    }
}

When ASP.NET Core creates ProductController, it resolves IProductService from the DI container and supplies an instance of ProductService to the constructor. The request flow is:
HTTP Request
     ↓
ASP.NET Core creates Controller
     ↓
DI Container resolves IProductService
     ↓
Provides ProductService instance
     ↓
Controller calls GetProduct()
     ↓
Returns "Laptop"

Service Lifetime in ASP.NET Core.

ASP.NET Core provides three commonly used service lifetimes.
Lifetime Behavior Typical Use
Transient Creates a new instance each time the service is requested Germany
Scoped Creates one instance per DI scope; in a typical web request, one instance per request Request-specific services, DbContext
Singleton Creates one instance for the DI container's lifetime Shared, thread-safe services and caches
Note: A singleton should not directly depend on a scoped service, such as a scoped DbContext, because the scoped service's lifetime is shorter. Doing so can cause a captive dependency and incorrect lifetime behavior.

 Q34. What is Inversion of Control (IoC)?

Inversion of Control (IoC) is a software design principle in which the responsibility for creating objects and managing their dependencies is transferred from the application classes to an external framework or container. Instead of a class controlling the creation of its dependencies, an external mechanism manages them and provides them when required.

IoC and DI are not exactly the same thing.

A design principle A design pattern/technique
Transfers control to an external mechanism Supplies dependencies from outside a class
Describes who controls object creation and dependency management Describes how dependencies are provided
DI is one way to implement IoC Commonly used to implement IoC

  • DI: Providing dependencies from outside instead of creating them inside a class.
  • IoC Container: Manages object creation, dependency resolution, and lifetimes.
  • IoC: A design principle that transfers control from application code to an external mechanism.

Q35. How do you create your own scoped services in ASP.NET Core?

We create manual scopes when we need to resolve scoped dependencies outside the normal HTTP request lifecycle, especially inside singleton services and background workers. Never inject a scoped service directly into a singleton, because it can create a captive dependency and lead to incorrect lifetime management.

We can create custom DI scopes using IServiceScopeFactory.CreateScope(). We then resolve scoped dependencies through scope.ServiceProvider. Once the scope is disposed, all scoped services created within that scope are disposed.

Example: Using IServiceScopeFactory

This is the commonly recommended approach when creating scopes inside a BackgroundService or singleton service.
public class OrderBackgroundService : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public OrderBackgroundService(
        IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        using var scope = _scopeFactory.CreateScope();

        var orderService = scope.ServiceProvider
            .GetRequiredService<IOrderService>();

        await orderService.ProcessOrdersAsync();
    }
}

Register Services in Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IOrderService, OrderService>();

builder.Services.AddHostedService<OrderBackgroundService>();

var app = builder.Build();

app.Run();

Here:
  • OrderBackgroundService is a singleton hosted service.
  • IOrderService is registered as Scoped.
  • IServiceScopeFactory creates a new scope.
  • GetRequiredService() resolves the scoped service from that scope.
  • using ensures that the scope and its scoped services are disposed of after processing.

Q36. Why do you prefer Autofac over built-in Microsoft DI?

Autofac is a third-party Inversion of Control (IoC) container for .NET. I would prefer Autofac over the built-in Microsoft DI container when an application requires advanced dependency injection features that are not available or are less convenient with the built-in container.

Autofac provides advanced dependency registration, module-based configuration, property injection, child lifetime scopes, custom lifetime management, decorators, and assembly scanning.

However, I don't always prefer Autofac. For most standard ASP.NET Core applications, the built-in Microsoft DI container is sufficient.

Q37. What exception do you get when a specific service that you injected can’t be found in the IoC container?

When ASP.NET Core cannot find a registered service in the built-in IoC container, it throws an InvalidOperationException.

This typically happens when we inject an interface or service into a constructor but forget to register its implementation in the DI container.
System.InvalidOperationException:

Unable to resolve service for type
'IProductService' while attempting to activate
'ProductController'.

Q38. What is the purpose of the launchSettings.json file?

launchSettings.json defines local development launch configurations for an ASP.NET Core application, including launch profiles, application URLs, ports, environment variables, and debugging settings. It is primarily used during development and is not required for production deployment.

File Location: Properties/launchSettings.jsonIt 
{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "MyApi-HTTP": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MyApi-HTTPS": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

ASPNETCORE_ENVIRONMENT
determines which environment-specific configuration and behavior the application uses.

Q39. What is the use of the appsettings.json file?

appsettings.json is the default configuration file in ASP.NET Core used to store application settings such as connection strings, logging configuration, API URLs, and custom settings. ASP.NET Core loads it through the configuration system, supports environment-specific files, and lets you access values using IConfiguration or the Options Pattern.

Example: appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=ProductDB;Trusted_Connection=True;TrustServerCertificate=True;"
  },

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },

  "AllowedHosts": "*",

  "ApplicationSettings": {
    "ApplicationName": "Product API",
    "MaxRetryCount": 3,
    "EnableCaching": true
  }
}

ASP.NET Core provides the IConfiguration interface to access configuration values.

var builder = WebApplication.CreateBuilder(args);

var appName = builder.Configuration
    ["ApplicationSettings:ApplicationName"];

var retryCount = builder.Configuration
    .GetValue<int>("ApplicationSettings:MaxRetryCount");

var connectionString = builder.Configuration
    .GetConnectionString("DefaultConnection");

You can also inject IConfiguration into a service or controller:
public class ProductService
{
    private readonly IConfiguration _configuration;

    public ProductService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public string GetApplicationName()
    {
        return _configuration["ApplicationSettings:ApplicationName"];
    }
}

Important Interview Points
  • appsettings.json separates configuration from application code.
  • It supports environment-specific configuration files.
  • You can access configuration values using IConfiguration.
  • It supports strongly typed configuration through the Options Pattern (IOptions<T>).
  • Do not commit sensitive information such as passwords, API secrets, and production credentials to source control. Use secure configuration providers such as AWS Secrets Manager, Azure Key Vault, or environment-based secrets.

Q40. Which configuration providers do you prefer for development and production environments in ASP.NET Core?

ASP.NET Core supports multiple configuration providers to manage application settings across different environments.
  • For development, commonly used providers include appsettings.json, appsettings.Development.json, User Secrets, and environment variables.
  • For production, use secure, centralized configuration providers such as AWS Secrets Manager, AWS Systems Manager Parameter Store, or Azure Key Vault to manage sensitive credentials and application settings.
The main objective is to separate configuration from application code, protect sensitive information, and allow configuration changes without modifying or rebuilding the application.

Q41. How do you use the Options pattern in Asp.Net Core?

The Options Pattern in ASP.NET Core is used to access application configuration settings through strongly typed C# classes instead of directly reading configuration values using string keys from IConfiguration.

It allows us to group related configuration settings into classes, bind them to sections in appsettings.json, and inject them into services or controllers using dependency injection. It improves type safety, maintainability, testability, and separation of concerns.

Step 1: Define Configuration in appsettings.json
{
  "EmailSettings": {
    "SmtpServer": "smtp.gmail.com",
    "Port": 587,
    "SenderEmail": "admin@example.com",
    "EnableSsl": true
  }
}

Step 2: Create a Strongly Typed Configuration Class
public class EmailSettings
{
    public string SmtpServer { get; set; }

    public int Port { get; set; }

    public string SenderEmail { get; set; }

    public bool EnableSsl { get; set; }
}

Step 3: Register the Options Pattern in Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<EmailSettings>(
    builder.Configuration.GetSection("EmailSettings"));

var app = builder.Build();

app.Run();

Here:
  • GetSection("EmailSettings") retrieves the configuration section.
  • Configure<EmailSettings>() binds the configuration values to the EmailSettings class.
  • ASP.NET Core registers the options configuration with the DI container.
Step 4: Inject Configuration Using IOptions<T>
using Microsoft.Extensions.Options;

public class EmailService
{
    private readonly EmailSettings _emailSettings;

    public EmailService(IOptions<EmailSettings> options)
    {
        _emailSettings = options.Value;
    }

    public void SendEmail()
    {
        Console.WriteLine(_emailSettings.SmtpServer);
        Console.WriteLine(_emailSettings.Port);
        Console.WriteLine(_emailSettings.SenderEmail);
    }
}

ASP.NET Core provides three commonly used options interfaces.
Interface Lifetime Behavior
IOptions Singleton-compatible Provides configuration values and does not automatically reload the options instance when configuration changes.
IOptionsSnapshot Scoped Provides a new options snapshot for each DI scope, typically each HTTP request.
IOptionsMonitor Singleton-compatible Provides current options values and supports change notifications when the configuration source supports reloading.
ss

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson