Tech Point Fundamentals

Sunday, November 27, 2022

.Net Core Interview Questions and Answers - Part 13

ASP.Net Core Interview Questions and Answers - Part 13

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 13th 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 to the current part:






ASP.Net Core Interview Questions and Answers - Part 13


Q124. What are the different ways to handle Errors and Exceptions in .Net Core applications? 

There are different ways to handle the errors and exceptions in ASP.Net Core applications.  ASP.NETCore middleware pipeline is always bidirectional:

  • The request is first entered into the ExceptionHandler middleware. While entering it is almost ignored, but while sending the response back it is the last middleware so that if the response contains any errors, modify the response and send a friendly message back to the client or execute the pipeline again. 
  • If ExceptionHandler not handling the errors webserver returns a status code to the user.

1. UseDeveloperExceptionPage() middleware: It is generally used for handling exceptions in the dev environment.


2. ExceptionHandler() middleware: It can be used for both prod and non-prod environments.



if (env.IsDevelopment())
{
   app.UseDeveloperExceptionPage();
}
else
{
   app.UseExceptionHandler("/Error");
   app.UseHsts();
}


For the development environment, the Developer exception page displays detailed information about the exception. You should place this middleware before any other middleware for which you want to catch exceptions. For prod environments, UseExceptionHandler middleware loads the proper Error page.



3. Lambda Exception Handler:

An alternative to a custom exception handler page is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the error before returning the response.

app.UseExceptionHandler(exceptionHandlerApp =>
{
exceptionHandlerApp.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;           
context.Response.ContentType = Text.Plain;

await context.Response.WriteAsync("An exception was thrown.");

var exceptionHandlerPathFeature =
context.Features.Get<IExceptionHandlerPathFeature>();

if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
await context.Response.WriteAsync(" The file was not found.");
}

if (exceptionHandlerPathFeature?.Path == "/")
{
await context.Response.WriteAsync(" Page: Home.");
}
});




You can also configure error code-specific pages in the Startup class Configure method:

app.Use(async (context, next) =>
{
    await next();
    if (context.Response.StatusCode == 404)
    {
        context.Request.Path = "/Not-Found";
        await next();
    }

if (context.Response.StatusCode == 403 || context.Response.StatusCode == 503 ||             context.Response.StatusCode == 500)
    {
        context.Request.Path = "/Home/Error";
        await next();
    }
});





Q125. What is the use of app.UseDeveloperExceptionPage() middleware in .Net Core applications? 

The Developer Exception Page displays detailed information about unhandled request exceptions. ASP.NET Core apps enable the developer exception page by default when running in the Development environment.

The developer exception page runs early in the middleware pipeline so that it can catch unhandled exceptions thrown in the middleware that follows. It can be only used in the dev because detailed exception information shouldn't be displayed publicly when the app runs in the Production environment. 

if (env.IsDevelopment())
{
   app.UseDeveloperExceptionPage();
}




The Developer Exception Page shows detailed stack traces for server errors. It uses DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. 

When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response. But if the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to HTML. The Developer Exception Page can include the following information about the exception and the request:



  1. Stack trace
  2. Query string parameters, if any
  3. Cookies, if any
  4. Headers

dev-exp-page

The Developer Exception Page isn't guaranteed to provide any information. So Logging is always required for complete error information. Also, don't enable the Developer Exception Page unless the app is running in the Development environment.




Q126. What is the difference between UseDeveloperExceptionPage and UseExceptionHandler?

In non-development environments, we use Exception Handling Middleware to produce an error payload (in API App) or an error response (in Web App). To configure a custom error handling page for the Production environment, the UseExceptionHandler is used.

The UseExceptionHandler exception handling middleware:

  1. Catches and logs unhandled exceptions.
  2. Re-executes the request in an alternate pipeline using the path indicated. The request isn't re-executed if the response has started. The template-generated code re-executes the request using the /Error path.
  3. But if the alternate pipeline throws an exception of its own, Exception Handling Middleware rethrows the original exception.

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



The Razor Pages app template provides an Error page (.cshtml) and PageModel class (ErrorModel) in the Pages folder. For an MVC app, the project template includes an Error action method and an Error view for the Home controller.

The exception-handling middleware re-executes the request using the original HTTP method. If an error handler endpoint is restricted to a specific set of HTTP methods, it runs only for those HTTP methods. 

For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its IgnoreApi property to true. This attribute configuration excludes the error handler action from the app's OpenAPI specification:

[ApiExplorerSettings(IgnoreApi = true)]

Allow anonymous access to the method if unauthenticated users should see the error.

The ExceptionHandling Middleware can also be used in the development environment as well to produce a consistent payload format across all environments.

if (app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/error-dev");
}
else
{
app.UseExceptionHandler("/error");
}




Q127. What is the app.UseStatusCodePages() middleware  in ASP.NETCore?

By default, an ASP.NET Core app doesn't provide a status code page for HTTP error status codes, such as 404 - Not Found. When the app sets an HTTP 400-599 error status code that doesn't have a body, it returns the status code and an empty response body. By using this middleware you can get different responses for different status codes. 

So to enable default text-only handlers for common error status codes, you need to call UseStatusCodePages in Program.cs:

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

app.UseStatusCodePages();



Please note that you have to call UseStatusCodePages before request handling middleware. For example, call UseStatusCodePages before the Static File Middleware and the Endpoints Middleware.

When UseStatusCodePages isn't used, navigating to a URL without an endpoint returns a browser-dependent error message indicating the endpoint can't be found. When UseStatusCodePages is called, the browser returns the following response:

Status Code: 404; Not Found

UseStatusCodePages isn't typically used in production because it returns a message that isn't useful to users. The status code page middleware does not catch exceptions. To provide a custom error handling page, use the exception handler page.

To customize the response content type and text, use the overload of UseStatusCodePages that takes a content type and format string:

app.UseStatusCodePages(Text.Plain, "Status Code Page: {0}");

Here the {0} is a placeholder for the error code. UseStatusCodePages with a format string isn't typically used in production because it returns a message that isn't useful to users.



Q128. What is UseStatusCodePagesWithRedirects middleware? What is the difference between UseStatusCodePages and UseStatusCodePagesWithRedirects?

The UseStatusCodePagesWithRedirects() extension method:

  1. Sends a new 302 - Found status code to the client.
  2. Then it Redirects the client to the error-handling endpoint provided in the URL template. The error handling endpoint typically displays error information and returns HTTP 200.

This method is commonly used when the app:

  1. Should redirect the client to a different endpoint, usually in cases where a different app processes the error. For web apps, the client's browser address bar reflects the redirected endpoint.
  2. Shouldn't preserve and return the original status code with the initial redirect response.

app.UseStatusCodePagesWithRedirects("/StatusCode/{0}");

The URL template can include a {0} placeholder for the status code. If the URL template starts with ~ (tilde), the ~ is replaced by the app's PathBase.  When specifying an endpoint in the app, create an MVC view or Razor page for the endpoint.






Q129. What is UseStatusCodePagesWithReExecute middleware? What is the difference between UseStatusCodePagesWithReExecute and UseStatusCodePagesWithRedirects? 

The UseStatusCodePagesWithReExecute extension method:

  1. Returns the original status code to the client.
  2. Generates the response body by re-executing the request pipeline using an alternate path.

This method is commonly used when the app should:

  1. Process the request without redirecting to a different endpoint. For web apps, the client's browser address bar reflects the originally requested endpoint.
  2. Preserve and return the original status code with the response.

If an endpoint within the app is specified, create an MVC view or Razor page for the endpoint.

app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");

The URL template must start with / and may include a placeholder {0} for the status code. To pass the status code as a query-string parameter, pass a second argument into UseStatusCodePagesWithReExecute. 

app.UseStatusCodePagesWithReExecute("/StatusCode", "?statusCode={0}");

The endpoint that processes the error can get the original URL that generated the error.







Q130. What is the SkipStatusCodePages attribute in ASP.Net MVC Core?

To disable status code pages for an MVC controller or action method, use the [SkipStatusCodePages] attribute.

[SkipStatusCodePages]
MyController()
{
}

To disable status code pages for specific requests in a Razor Pages handler method or in an MVC controller, use IStatusCodePagesFeature:

public void OnGet()
{
var statusCodePagesFeature =
HttpContext.Features.Get<IStatusCodePagesFeature>();

if (statusCodePagesFeature is not null)
{
statusCodePagesFeature.Enabled = false;
}
}



Q131. What is AddDatabaseDeveloperPageExceptionFilter() in ASP.Net Core Application?

The Database developer page exception filter AddDatabaseDeveloperPageExceptionFilter captures database-related exceptions that can be resolved by using Entity Framework Core migrations.

When these exceptions occur, an HTML response is generated with details of possible actions to resolve the issue. This page is enabled only in the Development environment. 

builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddRazorPages();



Q132. What is the difference between Exception filters and built-in UseExceptionHandler middlewares in ASP.Net Core?

In MVC Exception filters handle any unhandled exceptions that occur during the execution of a controller action or another filter.

In MVC apps, exception filters can be configured globally or on a per-controller or per-action basis. In Razor Pages apps, they can be configured globally or per page model.

Exception filters are useful for trapping exceptions that occur within MVC actions, but they're not as flexible as the built-in exception-handling middleware i.e UseExceptionHandler

Microsoft recommends using UseExceptionHandler unless you need to perform error handling differently based on which MVC action is chosen.






Q133. How can you handle model validation errors and exceptions in ASP.Net Core applications?

The model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors.

Both model binding and model validation occurs before the execution of a controller action or a Razor Pages handler method. For web apps, it's the app's responsibility to inspect ModelState.IsValid and react appropriately. Web apps typically redisplay the page with an error message.

For ASP.NET Core MVC with controllers and views:

if (!ModelState.IsValid)
{
return Page();
}



Web API controllers don't have to check ModelState.IsValid if they have the [ApiController] attribute. In that case, an automatic HTTP 400 response containing error details is returned when the model state is invalid. 

For Web API controllers, MVC responds with a ValidationProblemDetails response type when model validation fails. MVC uses the results of InvalidModelStateResponseFactory to construct the error response for a validation failure.

The following example replaces the default factory with an implementation that also supports formatting responses as XML, in Program.cs:

builder.Services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
new BadRequestObjectResult(context.ModelState)
{
ContentTypes =
{
// using static System.Net.Mime.MediaTypeNames;
Application.Json,
Application.Xml
}
};
})
.AddXmlSerializerFormatters();







Q134. How can you handle client responses for the user-defined custom exceptions? What is ProblemDetailsFactory middleware?

ASP.NET Core doesn't produce a standardized error payload when an unhandled exception occurs. For scenarios where it's desirable to return a standardized ProblemDetails response to the client, the ProblemDetails middleware can be used to map exceptions and 404 responses to a ProblemDetails payload.

The exception-handling middleware can also be used to return a ProblemDetails payload for unhandled exceptions.

In ASP.Net Core an error result is defined as a result with an HTTP status code of 400 or higher. For Web API controllers, MVC transforms an error result to produce a ProblemDetails.

MVC uses Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory to produce all instances of ProblemDetails and ValidationProblemDetails. This factory is used for:



  1. Client error responses
  2. Validation failure error responses
  3. ControllerBase.Problem and ControllerBase.ValidationProblem

To customize the problem details response, register a custom implementation of ProblemDetailsFactory in Program.cs:

builder.Services.AddControllers();
builder.Services.AddTransient<ProblemDetailsFactory, SampleProblemDetailsFactory>();

Use the ClientErrorMapping property to configure the contents of the ProblemDetails response.  For example, to update the Link property for 404 responses:

builder.Services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.ClientErrorMapping[StatusCodes.Status404NotFound].Link =
"https://httpstatuses.com/404";
});







To Be Continued Part-14...


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.