Tech Point Fundamentals

Sunday, January 8, 2023

.Net Core Interview Questions and Answers - Part 19

ASP.Net Core Interview Questions and Answers - Part 19

AspDotNetCoreInterviewQuestionsAndAnswers

Are you preparing for the .Net Core Interview? If yes, then you are at the right place. This is the ASP.Net Core Interview Questions and Answers article series. Here we will see the Top 150+ .Net Core Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:




Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.




Introduction


This is the 19th part of the .Net Core Interview Questions and Answers article series. Each part contains ten .Net Core Interview Questions. Please read all the .Net Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:






ASP.Net Core Interview Questions and Answers - Part 19


Q185. What is the difference between Routing in ASP.Net Core 2.0 and ASP.Net Core 3.0?

The ASP.NET Core 3.0 introduced a new Routing Module known as Endpoint Routing.   It is the Routing engine that decides to invoke the controller for a particular request.  It is also used to generate the outgoing URLs. 

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

Before .Net Core 3.0 we are using  UseMvc() or UseMvcWithDefaultRoute() middleware for configuring the routes. But now from  .Net Core 3.0 we can use UseEndpoints() method.

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




With conventional routing, you set up one or more conventions that will be used to match incoming URLs to endpoints in the app.   In ASP.NET Core, these endpoints may be Razor Pages, Health Checks, or SignalR hubs as well. All of these routable features are configured in a similar fashion using endpoints:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/healthz").RequireAuthorization();
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});

MapRoute vs MapControllerRoute:

MapControllerRoute is an extension method on the EndpointRouteBuilder and accepts the following argument:

name: The name of the route
pattern: The URL pattern of the route
defaults: An object that contains default values for route parameters. The object’s properties represent the names and values of the default values

constraints: An object that contains constraints for the route. The object’s properties represent the names and values of the constraints.
dataTokens: An object that contains data tokens for the route. The object’s properties represent the names and values of the data tokens.




Q186.  What is End Point? What is End Point Routing in ASP.Net Core?

Before ASP.NET Core 3.0 the Route resolution & invoking of the Route were part of the MVC Middleware. We defined the routes while configuring the MVC is using the app.UseMvc:

app.UseMvc(routes =>  {
  routes.MapRoute("default",
  "{controller}/{action}");           
});

EndPoint Routing is the new way to implement the Routing in ASP.NET Core 3.0. It splits up the old routing middle ware into two separate middleware and also decouples the MVC from the Routing Middleware. 

The Endpoint Routing is the Process by which ASP.NET Core inspects the incoming HTTP requests and maps them to the application executable Endpoint. 

We define the Endpoint during the application startup. The Routing Module then matches the incoming URL to an Endpoint and dispatches the request to it. 



The Endpoint Routing Module also decouples the route matching functions and endpoint dispatching functions using the two separate middleware.

  • The EndPointRoutingMiddleware resolves the HTTP request to an Endpoint (route matching).
  • The EndpointMiddleware invokes the Endpoint (endpoint dispatching). 

Endpoint:  

An Endpoint is an object that contains everything that you need to execute the incoming Request. The Endpoint object contains the following information:

  • Metadata of the request. 
  • The delegate (Request handler) that ASP.NET core uses to process the request.

We define the Endpoint at the application startup using the UseEndpoints method. The ASP.NET Core routing is now not tied up only to the MVC Endpoints. You can define an Endpoint, which can also hit a Razor page, SignalR, gRPC Services, etc.



Q187. How does the End Point Routing work in ASP.Net Core MVC?

EndPointRouting is responsible for matching incoming HTTP requests and dispatching those requests to the app's executable endpoints. Endpoints are the app's units of executable request-handling code. Endpoints are defined in the app and configured when the app starts

The endpoint matching process can extract values from the request's URL and provide those values for request processing. Using endpoint information from the app, routing is also able to generate URLs that map to endpoints.

The EndpointMiddleware is responsible for executing the Endpoint. We register it using the UseEndpoints() method. It reads the Endpoint, which was selected by the Route Matching middleware, and runs the delegate associated with it.

Routing finds matching executable endpoint for incoming requests. These endpoints are registered when the app starts. The matching process use values from the incoming request URL to process the requests.



Routing uses a pair of middleware, registered by UseRouting and UseEndpoints:

UseRouting adds route matching to the middleware pipeline. This middleware looks at the set of endpoints defined in the app and selects the best match based on the request.

UseEndpoints adds endpoint execution to the middleware pipeline. It runs the delegate associated with the selected endpoint. Endpoints that can be matched and executed by the app are configured in UseEndpoints.

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

The MapGet() method is used to define an endpoint. An endpoint is something that can be selected by matching the URL and HTTP method and executed, by running the delegate.

app.UseEndpoints(endpoints => 
endpoints.MapGet("/", async context => 
await context.Response.WriteAsync("Hello World!"); 
}); 
}); 



Q188. How can you define endpoints in ASP.Net Core?

Now the ASP.NET Core supports many scenarios in developing apps. They include web apps like MVC, Razor Pages & Blazor.  You can also build Web APIs or real-time Apps using SignalR. Use gRPC to build Remote Procedure call apps, etc.

The ASP.NET Core provides several extension methods to set up & configure the Endpoints. You can create an endpoint to custom delegates using the map methods like MapGet, MapPost, MapPut, MapDelete, & Map.

Use MapRazorPages to add all the required Endpoints which map to Razor Pages: 

endpoints.MapRazorPages();

Similarly, you can use the MapHub to configure the SignalR endpoint:

endpoints.MapHub<ChatHub>("/chathub");

You can use MapGrpcService  to Create an Endpoint to a gRPC service as well:

endpoints.MapGrpcService<SomeGrpcService>();




Q189. What is UseEndpoints() middleware in ASP.Net MVC Core?

The Endpoint Routing has three components:

  1. Defining the Endpoints.
  2. Route Matching & Constructing an Endpoint (UseRouting).
  3. Endpoint Execution (UseEndpoints).

We configure the Endpoint in the app.UseEndpoints method. 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{  
    app.UseHttpsRedirection();
    app.UseStaticFiles();
 
    app.UseRouting();
 
    app.UseAuthorization();
 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

          endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World");
});

    });
}



To set up an attribute-based routing use the method MapControllers. We use attribute-based Routing to create a route to Rest API (Web API Controller Action Method). You can also use it to create a route to the MVC Controller action method.

endpoints.MapControllers();

MapControllerRoute & MapControllers methods hide all the complexities of setting up the Endpoint from us. Both set up the Endpoint to Controller action methods. 

Remember, we also have to configure the endpoints route pattern in the UseEndpoints method. The EndpointMiddleware middleware is terminal Middleware when a match is found. The middleware after UseEndpoints executes only when no match is found.

You can also create an Endpoint to a custom delegate using the MapGet method. MapGet accepts two arguments. One is Route Pattern (/ in the example) and a request delegate.

endpoints.MapGet("/", async context =>
{
  await context.Response.WriteAsync("Hello World");
});



Q190. What is POST Tunneling Middleware in ASP.NET Core? What is UseHttpMethodOverride() middleware in ASP.Net Core?

HTTP methods include GET, PUT, POST, DELETE, HEAD, OPTIONS, TRACE, PATCH, and CONNECT. We can use HTTP methods to include additional endpoints in our applications without bloating the URI interface we provide our users. 

All HTML forms or views have an action attribute, with only two valid values: GET and POST. The restricted action values limit the possible ways our front end can communicate with our back end. 

There are various REST clients which don’t have capabilities to send PUT/ PATCH/ DELETE requests to your REST API and you want your REST API to be available on, if not all, then most platforms. 

POST Tunneling is a quite old technic. A lot of HTTP clients (including XMLHttpRequest in some browsers) weren't providing support for all HTTP methods. Also, many corporate network infrastructures were blocking certain methods. 



Previously in the .Net Framework, the solution was to tunnel such a method through a POST request with help of a custom header ( X-HTTP-Method-Override).

But ASP.NET Core ships with HttpMethodOverrideMiddleware, which allows our application to route a GET or a POST to an ASP.NET Core endpoint that has a different HTTP method.

 In the .Net Framework ASP.Net Web API, your clients would still send a POST call to your API, but with “X-HTTP-Method-Override: PUT” as a header, which makes your API consider the request as a PUT request in ASP.Net Web API.

But, if you want to do the same in .Net Core, that should be even more easier. The HTTPMethodOverride  Build-in Middleware which can be used to pipe into the .Net Core MVC Pipeline to convert the POST methods to PUT/ DELETE as needed. You need to register the HttpMethodOverrideMiddleware in our Startup class.

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




Q191. How can you enforce HTTPS in ASP.NET Core Project?

The UseHttpsRedirection() middleware forces HTTP calls to automatically redirect to equivalent HTTPS addresses. 

On the other hand UseHsts() middleware is used in production to enable HSTS (HTTP Strict Transport Security Protocol) and enforce HTTPS. 

Calling these methods next ensures that HTTPS can be enforced before resources are served from a web browser. 

Microsoft recommends that do not use RequireHttpsAttribute on Web APIs that receive sensitive information.  RequireHttpsAttribute uses HTTP status codes to redirect browsers from HTTP to HTTPS. API clients may not understand or obey redirects from HTTP to HTTPS. Such clients may send information over HTTP. 



The default API projects don't include HSTS (HTTP Strict Transport Security Protocol) because HSTS is generally a browser-only instruction. Other callers, such as phone or desktop apps, do not obey the instruction. 

Even within browsers, a single authenticated call to an API over HTTP has risks on insecure networks. The secure approach is to configure API projects to only listen to and respond over HTTPS.

Requests to an endpoint using HTTP that are redirected to HTTPS by UseHttpsRedirection fail with ERR_INVALID_REDIRECT on the CORS preflight request. API projects can reject HTTP requests rather than use UseHttpsRedirection to redirect requests to HTTPS.

if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();




Q192. What is OWIN? How can you use OWIN in ASP.NET Core?

OWIN (Open Web Interface for .NET) is a standard ( OWIN Specification) and Katana is a .NET library. OWIN defines a standard interface between .NET web servers and web applications. 

The goal of OWIN is to decouple web applications from the webserver by introducing an abstraction layer. Such an abstraction enables you to run the same application on all the web servers that support OWIN. Katana is a set of components by Microsoft built using OWIN specifications. Some of these components include Web API, ASP.NET Identity and SignalR.

ASP.NET Core Supports OWIN. It has .NET Core compatible replacements for the Microsoft.Owin.* (Katana) libraries. 

OWIN allows web apps to be decoupled from web servers. It defines a standard way for middleware to be used in a pipeline to handle requests and associated responses. ASP.NET Core applications and middleware can interoperate with OWIN-based applications, servers, and middleware.

OWIN provides a decoupling layer that allows two frameworks with disparate object models to be used together. The Microsoft.AspNetCore.Owin package provides two adapter implementations: ASP.NET Core to OWIN and OWIN to ASP.NET Core.

This allows ASP.NET Core to be hosted on top of an OWIN compatible server/host or for other OWIN compatible components to be run on top of ASP.NET Core. ASP.NET Core's OWIN support is deployed as part of Microsoft.AspNetCore.Owin package. You can import OWIN support into your project by installing this package.



Q193. What is SignalR in ASP.NET Core?

SignalR refers to a real-time application communication channel. It is a process that allows the integration of real-time functionality into your web applications. 

The SignalR Hubs API enables connected clients to call methods on the server. The server defines methods that are called from the client and the client defines methods that are called from the server. SignalR takes care of everything required to make real-time client-to-server and server-to-client communication possible.

The best example of a real-time-based application is a chat application, where the server sends content to the client as soon as it becomes available. SignalR can be used to push notifications within an application. It uses encryption and a digital signature to make a secure communication channel.

To register the services required by SignalR hubs, call AddSignalR in Program.cs. To configure SignalR endpoints, call MapHub, also in Program.cs:

builder.Services.AddSignalR();
app.MapHub<ChatHub>("/Chat");



Q194. What is a Secret Manager in ASP.Net Core?

It is always recommended that never store passwords or other sensitive data in source code. Secrets shouldn't be deployed with the app. Production secrets shouldn't be used for development or testing. Instead, production secrets should be accessed through controlled means like Environment Variables or Azure Key Vault

The Secret Manager tool stores sensitive data during the development of an ASP.NET Core project. App secrets are stored in a separate location from the project tree. The app secrets are associated with a specific project or shared across several projects.  The app secrets aren't checked into source control.

The Secret Manager tool doesn't encrypt the stored secrets and shouldn't be treated as a trusted store. It's for development purposes only. The keys and values are stored in a JSON configuration file in the user profile directory.

The Secret Manager tool hides implementation details, such as where and how the values are stored. You can use the tool without knowing these implementation details. The values are stored in a JSON file in the local machine's user profile folder. In Windows Machine, the secrets.json file path is:



%APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json

The Secret Manager tool operates on project-specific configuration settings stored in your user profile. The Secret Manager tool includes an init command. To use user secrets, run the following command in the project directory:

dotnet user-secrets init

This command adds a UserSecretsId element within a PropertyGroup of the project file. By default, the inner text of UserSecretsId is a GUID. The inner text is arbitrary but is unique to the project.

To Create User Secrets in Visual Studio, right-click the project in Solution Explorer, and select Manage User Secrets from the context menu.  This gesture adds a UserSecretsId element, populated with a GUID, to the project file.

You may notice that a JSON file secrets.json is now created.  Now cut the connection string node from the appsettings.json file and paste it into the secrets.json file. Build your project and run your application. It should work perfectly.


To Be Continued Part-20...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.

    

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.