Tech Point Fundamentals

Sunday, January 1, 2023

.Net Core Interview Questions and Answers - Part 18

ASP.Net Core Interview Questions and Answers - Part 18

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 18th part of the .Net Core Interview Questions and Answers article series. Each part contains ten to fifteen .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 18


Q175. What is Routing? How does routing work in ASP.Net Core? 

Routing is the process of directing an HTTP request to a controller. Routing is the process through which the application matches an incoming URL path and executes the corresponding action methods. 

In ASP.Net MVC the routing is defined in the route config file:

 public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();

// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}



But ASP.NET Core MVC uses a routing middleware to match the URLs of incoming requests and map them to specific action methods.

app.UseRouting();

In ASP.NET Core, routing is the process of mapping incoming requests to the route handler. The route can have arguments inside the URL which are then used to process the call. Routing works by finding the route handler based on the URL given. 

It is a process through which the incoming requests are mapped to the corresponding controllers and actions. The .NET Core MVC has a routing middleware to perform this task. The Routing Middleware is available in Microsoft.AspNetCore.Routing Namespace.



RoutingInCore
Source: tektutorialshub



The Routing has two main jobs:

  • It maps the incoming requests to the Controller Action
  • Generate outgoing URLs that correspond to controller actions.

So when a request arrives at the Routing Middleware it does the following.

  1. It parses the incoming request URL.
  2. Searches for the Matching Route in the available RouteCollection.
  3. If a matching route is found then it passes the control to the RouteHandler.
  4. If the route is not found, it gives up and invokes the next Middleware in the pipeline.




Q176. What is the difference between Route, RouteCollection, and Route Handler?

The Route is similar to a roadmap that we use to go to our destination. Similarly, the ASP.NET Core Apps use the Route to go to the controller action.  In MVC each Route contains a valid Name, URL Pattern, Route Defaults, and Constraints. The URL Pattern is compared to the incoming URLs for a match. The Route is defined in Microsoft.AspNetCore.routing namespace.

A Route Collection is the collection of all the available Routes in the Application. The app maintains a single in-memory collection of Routes. The Routes are added to this collection when the application starts. The Routing Module looks for a Route that matches the incoming request URL on each available Route in the Route collection. The Route  Collection is also defined in Microsoft.AspNetcore.routing namespace.



The Route handler is the class that implements the IRouteHandler interface. In the ASP.NET Core, the Routes are handled by the MvcRouteHandler.

The Route Handler is the Component that decides what to do with the route. When the routing Engine locates the Route for an incoming request, it invokes the associated RouteHandler and passes the Route for further processing. 

MVCRouteHandler is the Default Route Handler for the ASP.NET Core MVC Middleware. The MVCRouteHandler is registered when we register the MVC Middleware in the Request Pipeline. 

The MVCRouteHandler is defined in the namespace Microsoft.AspnetCore.MVC. The MVCRouteHandler is responsible for invoking the Controller Factory, which in turn creates the instance of the Controller associated with the Route.



Q177. What is the different between UseMvcWithDefaultRoute() method and UseMvc() middleware in ASP.Net Core MVC?

We can add the required MVC middleware into the request processing pipeline either by calling the UseMvcWithDefaultRoute() method or by calling the UseMvc() method in the Configure() method of the Startup.cs class file.

Adding routes via the UseMvc method, also known as the conventional way of adding MVC routes, is a way of defining all routes in a central location. The app.UseMvcWithDefaultRoute() tells ASP.NET Core MVC to create a default route that interprets incoming request URLs according to the MVC convention.

Actually, if you see the implementation of the UseMvcWithDefaultRoute() method here it is using the UseMvc method internally which is adding the default route into the application’s request processing pipeline.



UseMvcWithDefaultRoute

On the other hand, you have to provide the default route path manually in the case of UseMvc(). 

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



Q178. What is the difference between MapControllerRoute vs MapDefaultControllerRoute vs MapControllers in ASP.Net Core MVC?

If you are upgrading .NET Core 2.1 to .NET Core 3.0, here you have to use UseEndpoints.

Endpoint routing (app.UseEndpoints) emphasizes Endpoint and route, Its core purpose is to The request landing point is decoupled from the routing addressing mode.

MapControllerRoute:

It adds endpoints for controller actions to Microsoft.AspNetCore.Routing.IEndpointRouteBuilder and specifies a route with the given name, pattern, defaults, constraints, and data tokens. The URL pattern constructs the route (conventional routing), usually used in MVC projects.

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

It was used in the early MVC web projects. Nowadays, conventional routing is not the mainstream, because the so-called conventional routing is not friendly to user browsing. 

Actually, Users should not be allowed to URL to match the developer-defined Controller-Action name, Instead, let developers match what users want to use URL, In this way, feature routing appears.



MapDefaultControllerRoute:

It is a shorthand for the configuration of the above default pattern. It ad the above default route internally by default. So MapDefaultControllerRoute is basically the same as MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"). 

In the above both patterns are basically:

 {{root_url}}/{{name_of_controller}}/{{name_of_action}}/{{optional_id}} 

where, if controller and action are not supplied, it defaults to home/index.

MapControllers:

It adds endpoints for controller actions to Microsoft.AspNetCore.Routing.IEndpointRouteBuilder without specifying any routes. Make no assumptions about the agreed route,.

It does not use conventional routing, instead, it is user-dependent feature routing used in Web API.




Q179. What is Route URL Pattern in ASP.Net Core MVC?

URL Pattern is a way to define the route pattern in MVC. A URL pattern can contain the literal values and variable placeholders known as URL parameters. Each route must contain a URL pattern. This pattern is compared with the incoming URL. If the pattern matches the URL, then it is used by the routing system to process that URL.

Each URL Pattern can consist of one or more “segments.”  The Segments are delimited by the forward-slash (/) character. Each segment can be either a Constant (literal) or Route Parameter. Each segment in the incoming URL is matched to the corresponding segment in the URL Pattern.

The Route Parameters are wrapped in curly braces for example {controller}, {action}. The Route Parameters can have default values like {controller=Home}, where Home is the default value for the controller. An equals = sign followed by a value after the Route Parameter name defines a default value for the parameter.



For example: {controller=Home}/{action=Index}/{id?}

The ? in {id ?} indicates that it is optional. A question mark? after the route parameter name defines the parameter as optional.

The above example registers a route where the first part of the URL is the Controller, and the second part is the action method to invoke on the controller. The third parameter is additional data in the name of id.

You can also have the Constant segments as well. Here, the admin is a Constant and must be present in the requested URL.

admin/{controller=Home}/{action=Index}/{id?}

The above URL pattern is not the same as below one:

{admin}/{controller=Home}/{action=Index}/{id?}

We have added Route Parameter admin to the route. Note that Route Parameter is enclosed in curly braces.

The main difference between the above two routes is that the admin is defined as Constant (without curly braces) in the previous URL pattern. This means the first segment of the URL must contain the word admin.

So /Home will not be matched in the first URL pattern but it will be matched in the second pattern (Admin=Home). But /Home/Index will not be matched in either pattern.




Q180. What is Default Route? How can you define multiple routes in ASP.Net MVC Core?

The default route table contains a single route (named Default).  The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id. 

routes.MapRoute(
"Default",                                             
"{controller}/{action}/{id}",                          
new { controller = "Home", action = "Index", id = "" } 

The Default route includes defaults for all three parameters. If you don't supply a controller, then the controller parameter defaults to the value Home. If you don't supply an action, the action parameter defaults to the Value Index. Finally, if you don't supply an id, the id parameter defaults to an empty string.

In MVC Core Route Defaults can be specified in two ways. One way is to use the equal sign like:

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



The second way is to use the third argument of the MapRoute method.

routes.MapRoute("default", 
"{controller}/{action}",                                
new { controller = "Home", action = "Index" });

Multiple Routes:

But sometimes we need multiple routes as well. You can configure the ASP.NET Core to handle any no of routes but each route must have a Unique and valid Name.

app.UseMvc(routes => {
 routes.MapRoute("authorisedOnly",
  "authorisedOnly",
  new { Controller = "Admin", Action = "Index" });

 routes.MapRoute("default",
"{controller=Home}/{action=Index}");
});

But please remember that the order matters because the first matching route always wins. So the order in which routes are registered is very important. URL Matching starts at the top and enumerates the collection of Routes searching for a match. It stops when it finds the first match.





Q181. What are the different types of routing in ASP.Net Core?

There are two types of Routing:

  1. Conventional Routing
  2. Attribute Routing
We can define the routes either in the startup code or as attributes. They describe how we can match the URL paths with the action methods. We can also use routes to generate URLs for links that are sent out in responses.

Generally, the Attribute-based routing is used in the REST API while Conventional Routing is used with controllers and views.

The .Net core supports both routing but always attributes routing bypass conventional routing. Both routing systems can co-exist in the same system.

Apps can configure routing using:

  1. Controllers
  2. Razor Pages
  3. SignalR
  4. gRPC Services
  5. Endpoint-enabled middleware such as Health Checks.
  6. Delegates and lambdas registered with routing.




Q182. What is Conventional based Routing in ASP.Net Core?

In Conventional Based Routing, the route is determined based on the conventions defined in the route templates in the ASP.NET Core Startup.cs file. The Convention-based Routes are configured in the Configure method of the Startup class.

Conventional based routing is typically used with the controllers and views. It creates routes based on a series of conventions. We define it using the endpoints.MapControllerRoute method.

MVC configures the default route template as {controller=Home}/{action=Index}/{id?}. This will match the Index() method in HomeController with an optional parameter id by default.

Conventional Routing establishes a convention for the URL path, such that given a template: "{controller=Home}/{action=Index}/{id?}"

  • First token maps to a controller
  • Second token maps to an action
  • Third token maps to an optional id action parameter



The Routing is handled by the Router Middleware. ASP.NET MVC adds the routing Middleware to the Middleware pipeline when using the app.UseMVC or app.UseMvcWithDefaultRoute.

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

The app.UseMvc method gets an instance of the RouteBuilder class  The RouteBuilder has an extension method MapRoute which allows us to add Route to the Routes Collection. But remember that you have to provide the route path in the UseMvc(). 

You can also use the UseEndPoints() as well in .Net Core 3.0 and later versions.

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "blog",
pattern: "blog/{*article}",
defaults: new { controller = "Blog", action = "Article" });
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Books}/{action=Details}/{id?}");
});

MapControllerRoute is an extension method on the EndpointRouteBuilder.



Q183. What is Attribute-based Routing in ASP.Net Core?

By placing a route on the controller or the action method, we can make use of the Attribute Routing feature. Attribute Routing maps URLs by applying the routing template directly on the controller and action. The existence of controller and action in the template is not mandatory for attribute routing as it doesn’t play any part in the routing process.

It is recommended that you use this approach for most of your APIs. Furthermore, it will make your code more explicit and reduce routing errors that might be introduced as you add more controllers and actions.

To set up an attribute-based Routing use the method MapControllers. MapControllerRoute & MapControllers methods hide all the complexities of setting up the Endpoint from us. 

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});



We generally use the attribute-based Routing to create a route to Rest API but you can also use it to create a route to the MVC Controller action method as well.

[Route("api/Products")]
[ApiController]
public class ProductsController : Controller
{
}

We can also use Http[Verb] attributes for Attribute Routing:

[HttpGet("/books")]
public IActionResult ListBooks()
{   
}



We can also specify multiple different routes as well for an action method. Attribute routing supports defining multiple routes that reach the same action. The most common usage of this is to achieve the functionality of the default conventional route:

[Route("")]
[Route("Home")]
[Route("Home/Index")]
public IActionResult Index()
{
return View();
}

When using Attribute Routing, the controller name and action method name play no role in selecting which action method to execute. 

Route attributes defined on the controller are combined with route attributes on the individual action methods to form the complete URL. It is known as the global prefix in attribute routing.

[Route("api")]
public class BaseController : Controller
{
}

Any route templates defined on the controller are prepended to route templates on all of its action methods. When we place a route attribute on the controller, all actions in the controller use attribute routing.




Q184. What is the use of UseRouting() middleware in ASP.Net Core? How it is different from UseEndPoints()?

The EndPointRoutingMiddleware resolves the incoming HTTP requests and constructs an Endpoint. We register it very early in the middleware pipeline using the UseRouting method.  The purpose of UseRouting() middleware is:

  1. Parse the incoming URL
  2. Resolve the URL and construct the Endpoint.
  3. Updates the HTTP Context object with the endpoint using the SetEndpoint method.

The Endpoint objects are immutable and cannot be modified after creation. The Middleware running after UseRouting can access the endpoint from the HTTP Context and take action. For example app.UseHttpsRedirection() and   app.UseStaticFiles() middleware cannot access the Endpoint.

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:

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. 

Remember, we also configure the endpoints 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.

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



When the app starts, UseRouting registers the Route Matching Middleware EndPointRoutingMiddleware. UseEndpoints method registers the Endpoint execution middleware EndpointMiddleware. UseEndpoints also configures the Endpoints.

When the request arrives to root URL / or to the /hello URL, the Route Matching Middleware will construct the Endpoint and updates the context. The later in the middleware the EndpointMiddleware reads the Endpoint from the context and executes its delegate.

Any request other than the above, will not have any Endpoints, and hence will throw the 404 error. Also, note that MapGet maps to HTTP GET requests only. Any other request like POST, PUT, etc returns a 404 status code.




To Be Continued Part-19...


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.