• Register
300 points
8 4 2

What Configure() method does in Startup.cs?

The Configure method is used to specify how the ASP.NET application will respond to HTTP requests. The request pipeline is configured by adding middleware components to an IApplicationBuilder instance that is provided by dependency injection. There are some built-in middlewares for error handling, authentication, routing, session and diagnostic purpose. Highlighted lines in below code, are built-in Middleware with ASP.NET Core 1.0.

 

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

    loggerFactory.AddConsole(Configuration.GetSection("Logging"));

    loggerFactory.AddDebug();

  

    app.UseApplicationInsightsRequestTelemetry();

  

    if (env.IsDevelopment())

    {

        app.UseBrowserLink();

        app.UseDeveloperExceptionPage();

    }

    else

    {

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

  

        // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859

        try

        {

            using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()

                .CreateScope())

            {

                serviceScope.ServiceProvider.GetService<ApplicationDbContext>()

                        .Database.Migrate();

            }

        }

        catch { }

    }

  

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

    app.UseStaticFiles();

    app.UseIdentity();

  

    // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

  

    app.UseMvc(routes =>

    {

        routes.MapRoute(

            name: "default",

            template: "{controller=Home}/{action=Index}/{id?}");

    });

}






 

What is the environment variable in the Dotnet core?

If you are using more than one connectionString then you can take advantage to set an environment variable. You can create multiple appsetting.json files like appsettings.dev.json, appsettings.qa.json, etc. Following code for retrieving your environment variable which you can set in launchSettings.json

 

//To retrieve your environment variable

       static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)

        {

            var env = ctx.HostingEnvironment;

            config.SetBasePath(env.ContentRootPath)

                .AddEnvironmentVariables()

                .AddInMemoryCollection()

                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);

            config.Build();

        }





 

What is the use of ConfigureServices method of startup class?

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.



 

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

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.



 

What is Kestral?

Kestrel is a cross-platform web server for ASP.NET Core based on libuv, a cross-platform asynchronous I/O library. Kestrel is the web server that is included by default in ASP.NET Core new project templates. If your application accepts requests only from an internal network, you can use Kestrel by itself.

 

If you expose your application to the Internet, you must use IIS, Nginx, or Apache as a reverse proxy server. A reverse proxy server receives HTTP requests from the Internet and forwards them to Kestrel after some preliminary handling. The most important reason for using a reverse proxy for edge deployments (exposed to traffic from the Internet) is security. Kestrel is relatively new and does not yet have a full complement of defenses against attacks.



 

What is WebListener?

ASP.NET Core ships two server implementations Kestral and WebListener. WebListener is also a web server for ASP.NET Core that runs only on Windows. It’s built on the Http.Sys kernel mode driver. WebListener is an alternative to Kestrel that can be used for direct connection to the Internet without relying on IIS as a reverse proxy server.



 

How to handle errors in middleware?

You can capture synchronous and asynchronous exception instances from the middleware pipeline and generate an HTML response. Following code has If the condition in which you can call different methods for development, staging, production environment or you can pass the environment name in IsInvironment extension method.

 

Also, you can configure a custom error handling page to call the UseExceptionHandler method that adds a middleware to a pipeline that will catch the exception, log them, Re-executes the request in an alternate pipeline for the page or controller indicated. The request isn't re-executed if the response has started.

 

if (env.IsDevelopment())

{

   app.UseDeveloperExceptionPage();

}

else

{

   app.UseExceptionHandler("/Error");

   app.UseHsts();

}

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

We can use both the methods in Configure methods of startup class. Both are used to add middleware delegate to the application request pipeline. The middleware adds using IApplicationBuilder.Use may call the next middleware in the pipeline whereas the middleware adds using IApplicationBuilder.Run method never calls the subsequent ore next middleware. After IApplicationBuilder.Run method, system stop adding middleware in request pipeline.



 

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

It is used for branching the pipeline. It branches the ASP.NET Core pipeline based on request path matching. If request path starts with the given path, middleware on to that branch will execute.

 

 

 public void Configure(IApplicationBuilder app)

 {

 app.Map("/path1", Middleware1);

 app.Map("/path2", Middleware2);

 }



 

What is a Host and what’s the importance of Host in ASP.NET Core application?

ASP.NET Core apps require a host in which to execute. The host is responsible for application startup and lifetime management. Other responsibility of host’s includes ensuring the application’s services and the server are available and properly configured. Don’t confuse yourself with a Server. The host is responsible for starting the app and its management, where the server is responsible for accepting HTTP requests. The host is configured to use a particular server; the server is unaware of its host.

 

The host is typically created using an instance of a WebHostBuilder, which builds and returns a WebHost instance. The WebHost references the server that will handle requests.

public class Program

    {

        public static void Main(string[] args)

        {

            var host = new WebHostBuilder()

                .UseKestrel()

                .UseContentRoot(Directory.GetCurrentDirectory())

                .UseIISIntegration()

                .UseStartup<Startup>()

                .Build();

 

            host.Run();

        }

    }



 

300 points
8 4 2