DOT NET CORE Basic Interview Question and Answers

Q) What is the startup class in ASP.NET core?

A) Startup class is the entry point of the ASP.NET Core application.  This class contains the application configuration related items. It is not necessary that class name must "Startup", it can be anything, we can configure startup class in Program class.

public class Program

 {

 public static void Main(string[] args)

 {

 CreateWebHostBuilder(args).Build().Run();

 }

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

 WebHost.CreateDefaultBuilder(args)

 .UseStartup<TestClass>();

 }

-----------------------------------------------------------------------------------------------------------------------------

Q) What is the use of Configure Services method of startup class?

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

(or)

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

-----------------------------------------------------------------------------------------------------------------------------

Q) What is middleware?

Middleware in ASP.NET Core refers to software components that are assembled into an application pipeline to handle requests and responses. Each middleware component can choose whether to pass the request to the next component in the pipeline and can perform work before and after the next component.

Key characteristics and functions of ASP.NET Core Middleware:

Request/Response Handling: Middleware components are designed to process incoming HTTP requests and outgoing HTTP responses. They form a chain, where each component can inspect, modify, or even short-circuit the request/response flow.

  • Pipeline Execution: 
    Middleware components are executed in a specific order, forming a pipeline. The order in which they are added to the pipeline is crucial, as it determines the sequence of operations.
  • Built-in and Custom: 
    .NET Core provides many built-in middleware components for common tasks (e.g., authentication, routing, static file serving, exception handling). Developers can also create custom middleware to implement specific application logic.
  • Configuration: 
    Middleware components are configured in the Configure method of the application's Startup class (or directly within Program.cs in newer .NET versions) using methods like UseRun, and Map on the IApplicationBuilder interface.

app.Use()

  • app.use is used to register middleware components in the application's request pipeline.
  • Middleware registered with app.use can perform actions on the incoming request and/or outgoing response, and then optionally pass the request to the next middleware in the pipeline using a next delegate or function.
  • This allows for a chain of responsibility where multiple middleware components can process a request sequentially.
  • Examples include logging middleware, authentication middleware, error handling middleware, or static file serving middleware.

Example:

Code


    app.Use(async (context, next) =>

    {

        // Do something before the next middleware

        await next.Invoke(); // Call the next middleware

        // Do something after the next middleware

    });

app.Run()

Purpose: app.Run() adds a middleware component that terminates the request pipeline. It generates a response and prevents any subsequent middleware components from executing.


  • Once app.run is executed, no subsequent middleware in the pipeline will be invoked for that request.
  • It is typically used to define the final action for a specific route or to provide a default response if no other middleware has handled the request. 

Example:

Code


    app.Run(async context =>

    {

        await context.Response.WriteAsync("Hello from app.Run!"); // Terminate the pipeline with this response

    });

In summary:






  • app.MapThis method creates a branch in the middleware pipeline based on a matching request path. It allows you to define a separate, isolated middleware pipeline that only executes for requests whose paths match a specified prefix.(OR)
  • app.Map 
    branches the pipeline, allowing specific middleware to run only for requests matching a particular path.
Code
    app.Map("/api", apiApp =>    {        apiApp.Run(async context =>        {            await context.Response.WriteAsync("Hello from API branch!");        });    });
Examples of common middleware:
  • UseDeveloperExceptionPageCatches exceptions and displays detailed error information during development.
  • UseHttpsRedirectionRedirects HTTP requests to HTTPS.
  • UseStaticFilesServes static files like CSS, JavaScript, and images.
  • UseRoutingMatches incoming requests to defined routes.
  • UseAuthentication and UseAuthorizationHandle user authentication and authorization.

-----------------------------------------------------------------------------------------------------------------------------

Q) What is routing in ASP.NET Core?

A) Routing is functionality that map incoming request to the route handler. The route can have values (extract them from URL) that used to process the request. Using the route, routing can find route handler based on URL. All the routes are registered when the application is started. There are two types of routing supported by ASP.NET Core

The conventional routing

Attribute routing

The Routing uses routes for map incoming request with route handler and Generate URL that used in response. Mostly, the application having a single collection of routes and this collection are used for the process the request. The RouteAsync method is used to map incoming request (that match the URL) with available in route collection.

-----------------------------------------------------------------------------------------------------------------------------

Q) How to enable Session in ASP.NET Core?

A) The middleware for the session is provided by the package Microsoft.AspNetCore.Session. To use the session in ASP.NET Core application, we need to add this package to csproj file and add the Session middleware to ASP.NET Core request pipeline.

public class Startup

 {
public void ConfigureServices(IServiceCollection services)

 {

 ….

 ….

 services.AddSession();

 services.AddMvc();

 }

 public void Configure (IApplicationBuilder app, IHostingEnvironment env)

 {

 ….

 ….

 app.UseSession();

 ….

 ….

 }

 }

-----------------------------------------------------------------------------------------------------------------------------

Q) What are the various JSON files available in ASP.NET Core?

There are following JSON files in ASP.NET Core:

global. Json

launchsettings.json

appsettings.json

bundleconfig.json

bower. Json

package. Json

-----------------------------------------------------------------------------------------------------------------------------


Q) Describe the Dependency Injection?

A)Dependency injection (DI) is a software design pattern that allows us to separate the dependencies of a class from its implementation. This makes our code more loosely coupled and easier to test.

In .NET Core, dependency injection is implemented using the IServiceProvider interface. This interface provides a way to register services with the DI container and then inject those services into classes that need them.

To use dependency injection in .NET Core, we need to do the following:

Create an interface that defines the contract for our dependency.
Create a class that implements the interface.
Register the service with the DI container.
Inject the service into the class that needs it.
Implementing Dependency Injection In .NET Core
Here is an example of how to use dependency injection in .NET Core:

Consider a scenario where you want to fetch all the categories from the database and want to show that in the UI layer. So, you will create a service, i.e., a Web API which will be called by the UI layer. Now, in API, we need to create one GET method, which will call the repository, and the repository talks with the database. In order to call the repository, we need to create an instance of the same in the API GET method, which means it’s mandatory to create an instance of the repository for API. We can say the instance of the repository is the dependency of API. Let’s see how we can inject this dependency into our core Web API.

Open Visual Studio and create a new project

Select API as a template and press OK.


Dependency Injection In .NET Core 
As we will fetch the categories, let’s create a category model with two fields - CategoryId and CategoryName. 


namespace DIinCore
{
    public class Category
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
    }
}
C#
Create an interface of the repository having the GetCategories method, which returns the list of category objects.

using System.Collections.Generic;

namespace DIinCore
{
    public interface ICategoryRepository
    {
        List<Category> GetCategories();
    }
}
C#
Implement the preceding interface and return some sample data. As our target is to understand dependency injection, here, we are not going to fetch the data from the database but rather returning hard coded ones.

using System.Collections.Generic;

namespace DIinCore
{
    public class CategoryRepository : ICategoryRepository
    {
        public List<Category> GetCategories()
        {
            List<Category> categories = new List<Category>();

            Category category = new Category() { CategoryId = 1, CategoryName = "Category1" };
            categories.Add(category);

            category = new Category() { CategoryId = 2, CategoryName = "Category2" };
            categories.Add(category);

            return categories;
        }
    }
}
C#
Assume that we are not aware of the dependency injection. Then, how will we expose the GET method from API? We used to create an instance of CategoryRepository and call the GetCategories method using that instance. So tomorrow, if there is a change in CategoryRepository, it will directly affect the GET method of API as it is tightly coupled with that.

[HttpGet]
public async Task<IActionResult> Get()
{
    CategoryRepository categoryRepository = new CategoryRepository();
    List<Category> categories = categoryRepository.GetCategories();

    return Ok(categories);
}
C#
With the .NET Framework, we used to use containers like LightInject, NInject, Unity, etc. But in .NET Core, Microsoft has provided an in-built container. We need to add the namespace, i.e., Microsoft.Extension.DependencyInjection.

So, in the startup class, inside the ConfigureServices method, we need to add our dependency into the service collection, which will dynamically inject whenever and wherever we want in the project. Also, we can mention which kind of instance we want to inject - the lifetime of our instance.
  • Transient: A new instance is created every time the service is requested.
  • Scoped: A new instance is created once per client request (e.g., per HTTP request in a web application).
  • Singleton: A single instance is created the first time it's requested and reused throughout the application's lifetime.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace DIinCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            // Registering a singleton service
            services.AddSingleton<ICategoryRepository, CategoryRepository>();

            // Other dependency injections can be added here using AddTransient or AddScoped
            // services.AddTransient<ICategoryRepository, CategoryRepository>();
            // services.AddScoped<ICategoryRepository, CategoryRepository>();

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}
C#
So far, we have added our dependency to the collection. It’s time to inject where we need it, i.e., in the Web API. Our GET method is inside the CategoryController, and we want an instance of categoryrepository. So, let’s create a CategoryController constructor which expects the ICategoryRepository type. From this parameterized constructor, set the private property of type ICategoryRepository, which will be used to call GetCategories from the GET method.

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace DIinCore.Controllers
{
    [Route("api/Category")]
    public class CategoryController : Controller
    {
        private ICategoryRepository categoryRepository { get; set; }

        public CategoryController(ICategoryRepository categoryRepository)
        {
            this.categoryRepository = categoryRepository;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            List<Category> categories = categoryRepository.GetCategories();
            return Ok(categories);
        }
    }
}
C#
Run the application, and we will be able to see the result of the GET method of CategoryController. Now, even though we haven’t created an instance of CategoryRepository, which is expected by CategoryController, we are able to call the GET method successfully. The instance of CategoryRepository has been resolved dynamically, i.e., our Dependency Injection.


Dependency Injection In .NET Core 
You can download the sample code from the top of this article.

Advantages of using dependency injection in .NET Core
Here are some of the advantages of using dependency injection in .NET Core:

Loose coupling: Dependency injection allows us to decouple our classes from their dependencies. This makes our code more maintainable and easier to test.
Testability: Dependency injection makes our code more testable because we can mock out dependencies in our unit tests.
Extensibility: Dependency injection makes our code more extensible because we can easily swap out dependencies.
Reusability: Dependency injection makes our code more reusable because we can easily share dependencies between different classes.
What are the different types of dependency injection?
There are 3 main types of dependency injection: constructor injection and property injection.
Constructor injection: Constructor injection is the most common type of dependency injection. In constructor injection, we inject the dependency into the class constructor.
Property injection: Property injection is less common than constructor injection. In property injection, we inject the dependency into a property of the class.
Method Injection: Dependencies are passed as arguments to a specific method of the class.
-----------------------------------------------------------------------------------------------------------------------------
Q) How can we inject the service dependency into the controller?
There are three easy steps to add custom service as a dependency on the controller.
Step 1: Create the service
 public interface IHelloWorldService
 {
 string Says Hello();
 }
 
 public class HelloWorldService: IHelloWorldService
 {
 public string Says Hello()
 {
 return "Hello ";
 }
 }
Step 2: Add this service-to-Service container (service can either added by singleton, transient or scoped)
 public void ConfigureServices(IServiceCollection services)
 {
 ….
 …
 services.AddTransient<IHelloWorldService, HelloWorldService>();
 …
 …
 }
Step 3: Use this service as a dependency in the controller
 public class HomeController: Controller
 {
 IHelloWorldService _helloWorldService;
 public HomeController(IHelloWorldService helloWorldService)
 {
 _helloWorldService = helloWorldService;
 }
 }
-----------------------------------------------------------------------------------------------------------------------------
Q) How to specify service lifetime for register service that added as a dependency?
A) ASP.NET Core allows us to specify the lifetime for registered services. The service instance gets disposed of automatically based on a specified lifetime. So, we do not care about the cleaning these dependencies, it will take care by ASP.NET Core framework. There are three types of lifetimes.
Singleton:
ASP.NET Core will create and share a single instance of the service through the application life. The service can be added as a singleton using AddSingleton method of IServiceCollection. ASP.NET Core creates service instance at the time of registration and subsequence request use this service instance. Here, we do not require to implement Singleton design pattern and single instance maintained by the ASP.NET Core itself.
Ex:  services.AddSingleton<IHelloWorldService, HelloWorldService>();
Transient:
ASP.NET Core will create and share an instance of the service every time to the application when we ask for it. The service can be added as Transient using AddTransient method of IServiceCollection. This lifetime can be used in stateless service. It is a way to add lightweight service.
Ex:  services.AddTransient<IHelloWorldService, HelloWorldService>();
Scoped:
ASP.NET Core will create and share an instance of the service per request to the application. It means that a single instance of service available per request. It will create a new instance in the new request. The service can be added as scoped using an AddScoped method of IServiceCollection. We need to take care while, service registered via Scoped in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject dependency via the constructor, it behaves like singleton object.
Ex: services.AddScoped<IHelloWorldService, HelloWorldService>();
-----------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------------

Q)  What is XSRF or CSRF? How to prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core?

A) Cross-Site Request Forgery (XSRF/CSRF) is an attack where attacker that acts as a trusted source send some data to a website and perform some action. An attacker is considered a trusted source because it uses the authenticated cookie information stored in browser.For example a user visits some site 'www.abc.com' then browser performs authentication successfully and stores the user information in cookie and perform some actions, In between user visits some other malicious site 'www.bad-user.com' and this site contains some code to make a request to vulnerable site (www.abc.com). It's called cross site part of CSRF.

-----------------------------------------------------------------------------------------------------------------------------

Q) How to prevent CSRF?

A) In ASP.NET Core 2.0 or later FormTaghelper automatically inject the antiforgery tokens into HTML form element.You can add manually antiforgery token in HTML forms by using @Html.AntiForgeryToken() and then you can validate it in controller by ValidateAntiForgeryToken() method.


-----------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------


FAQ:

Short notes:

DI Container (Service Container):

In .NET Core, this is a built-in system (implemented by IServiceProvider and configured via IServiceCollection) that manages the lifecycle of services and provides instances of dependencies when requested.

Injection:

The process of providing a required dependency from the DI container to a class. Common methods include:

Constructor Injection: Dependencies are passed as arguments to the class's constructor. This is the most common and recommended approach.

Property Injection: Dependencies are assigned to public properties of the class.

Method Injection: Dependencies are passed as arguments to a specific method of the class.


Register Services:

In your application's Startup.cs (or Program.cs in newer versions), you register your services with the DI container using methods like services.AddTransient, services.AddScoped, or services.AddSingleton. These methods also define the lifetime of the service:

Transient: A new instance is created every time the service is requested.

Scoped: A new instance is created once per client request (e.g., per HTTP request in a web application).

Singleton: A single instance is created the first time it's requested and reused throughout the application's lifetime.



-----------------------------------------------------------------------------------------------------------------



Introduction

In this article, we are going to discuss Custom Middleware. This is a second article on middleware. I recommend reading the first article here before continuing on this.

This article can be used by beginners, intermediates, and professionals.

We are going to cover,

  1. How to create custom Middleware?
  2. How to use custom middleware in the HTTP pipeline?

Let’s start with custom Middleware,

How to create custom Middleware?

Asp.net core provided many in-build Middleware but in some scenarios, we need our own middleware to fulfill our requirement, in such case will go with custom middleware.

In the first article, we have written inline middleware but in the real world, we will create a separate class for middleware that is called custom middleware. 

There are 2 ways to create Custom Middleware in Asp.net Core.

  1. Using IMiddleware interface
  2. Using the extension method.

Let’s try to learn how to create custom middleware using IMiddelware Interface the below example,

Step 1

Create a class and name it “CustomeMiddlewareDemo

namespace WebApplication1 {
    public class CustomMiddlewareDemo {}
}
C#

Step 2

Inherit “IMiddleware” interface from “Microsoft.AspNetCore.Http” namespace and implement it as per the below code.

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace WebApplication1 {
    public class CustomMiddlewareDemo: IMiddleware {
        public Task InvokeAsync(HttpContext context, RequestDelegate next) {
            throw new System.NotImplementedException();
        }
    }
}
C#

Step 3

Now we will add code for Custom middleware in the “InvokeAsync” method.

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace WebApplication1 {
    public class CustomMiddlewareDemo: IMiddleware {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next) {
            await context.Response.WriteAsync("Hellow from Custom Middleware");
            await next(context);
        }
    }
}
C#

You might notice that I have added async and await for “InvokeAsync” Method.

We have created a separate file for Custom Middleware and now we will learn how to use it.

How to use Middleware in the HTTP Pipeline?

We will consume newly created custom middleware in the HHTP pipeline.

As we know if want to use any kind of new services in the ASP.Net Core application then before we use we need to register startup.cs -> “ConfigureServices” method.

Before we use Custom middleware in the code, we will register in the “Configure Service” method.

Step 4

Configure CustomMiddleware in the “ConfigureService” Method.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1 {
    public class Startup {
        public Startup(IConfiguration configuration) {
            Configuration = configuration;
        }
        public IConfiguration Configuration {
            get;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            services.AddControllersWithViews();
            services.AddTransient < CustomMiddlewareDemo > ();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            } else {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
C#

Step 5

Now we will use CustomMiddleware in the HTTP Pipeline. For that, we will inject custom Middleware in the “Configure” method like below.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1 {
    public class Startup {
        public Startup(IConfiguration configuration) {
            Configuration = configuration;
        }
        public IConfiguration Configuration {
            get;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            services.AddControllersWithViews();
            services.AddTransient < CustomMiddlewareDemo > ();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            app.UseMiddleware < CustomMiddlewareDemo > ();
            app.Run(async context => await context.Response.WriteAsync("Hello"));
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            } else {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
C#

OUTPUT

Now we will create custom middleware using the extension method,

Step 1 - Add a new Middleware class to the project

Right Click on Project -> Add -> new item -> Asp.net Core -> Middleware class

Click on Add button and observed Middleware class code.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace WebApplication1 {
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class MyMiddleware {
        private readonly RequestDelegate _next;
        public MyMiddleware(RequestDelegate next) {
            _next = next;
        }
        public Task Invoke(HttpContext httpContext) {
            return _next(httpContext);
        }
    }
    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class MyMiddlewareExtensions {
        public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder) {
            return builder.UseMiddleware < MyMiddleware > ();
        }
    }
}
C#

Step 2

Add your custom code in the “Invoke” method of the Middleware class.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace WebApplication1 {
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class MyMiddleware {
        private readonly RequestDelegate _next;
        public MyMiddleware(RequestDelegate next) {
            _next = next;
        }
        public async Task Invoke(HttpContext httpContext) {
            await httpContext.Response.WriteAsync("Hellow Custom Middleware \n");
            await _next(httpContext);
        }
    }
    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class MyMiddlewareExtensions {
        public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder) {
            return builder.UseMiddleware < MyMiddleware > ();
        }
    }
}
C#

Step 3

Use Custom Middleware in the HTTP pipeline.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1 {
    public class Startup {
        public Startup(IConfiguration configuration) {
            Configuration = configuration;
        }
        public IConfiguration Configuration {
            get;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            services.AddControllersWithViews();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            app.UseMyMiddleware();
            app.Run(async context => await context.Response.WriteAsync("Hello"));
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            } else {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
C#

OUTPUT

That’s all for this article. Hope you enjoyed and learn how to create and configure Custom Middleware in the HTTP Pipeline.

Comments

Popular posts from this blog

Angular Basic concepts

Sql server interview questions for experienced