Tech Point Fundamentals

Sunday, January 22, 2023

.Net Core Interview Questions and Answers - Part 21

ASP.Net Core Interview Questions and Answers - Part 21

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 21st 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 21


Q204. What are the different ways of the Session and State management in ASP.NET Core?

As we know HTTP is a stateless protocol. HTTP requests are independent and do not retain user values.  We need to take additional steps to manage the state between the requests. 

There are the following different ways to maintain the user state between multiple HTTP requests.

  1. Cookies
  2. Session State
  3. TempData
  4. Query strings
  5. Hidden fields
  6. HttpContext.Items
  7. Cache



Q205. What are cookies? How can you enable cookies in ASP.Net Core?

Cookies store data in the user’s browser. Browsers send cookies with every request and hence their size should be kept to a minimum. Most browsers restrict cookie size to 4096 bytes and only a limited number of cookies are available for each domain.

A cookie is a small amount of data that is persisted across requests and even sessions. Cookies store information about the user. The browser stores the cookies on the user’s computer. Most browsers store the cookies as key-value pairs.

Users can easily tamper or delete a cookie. Cookies can also expire on their own. Hence we should not use them to store sensitive information and their values should not be blindly trusted or used without proper validation.

Because cookies are subject to tampering, they must be validated by the app. Cookies can be deleted by users and expire on clients. However, cookies are generally the most durable form of data persistence on the client.

//Set the key value in Cookie              
CookieOptions option = new CookieOptions();
option.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Append("UserName", userName, option);

//Read cookie from Request object  
 string userName = Request.Cookies["UserName"];

// Delete a cookie in ASP.NET Core
Response.Cookies.Delete(somekey);




Q206. What is Session State? How can you enable the session state in ASP.Net Core?

Session state is an ASP.NET Core scenario for storage of user data while the user browses a web app. Session state uses a store maintained by the app to persist data across requests from a client. 

ASP.NET Core maintains the session state by providing a cookie to the client that contains a session ID. The browser sends this cookie to the application with each request. The application uses the session ID to fetch the session data.

The session data is backed by a cache and considered ephemeral data. The site should continue to function without the session data. Critical application data should be stored in the user database and cached in session only as a performance optimization.

The session isn't supported in SignalR apps because a SignalR Hub may execute independent of an HTTP context.  

Don't store sensitive data in session state. The user might not close the browser and clear the session cookie. Some browsers maintain valid session cookies across browser windows. A session might not be restricted to a single user. The next user might continue to browse the app with the same session cookie.

ASP.NET Core maintains the session state by providing a cookie to the client that contains a session ID. The cookie session ID is sent to the app with each request. It is used by the app to fetch the session data.



Session Fundamental Points:

While working with the Session state, we should keep the following things in mind:
  1. A session cookie is specific to the browser so sessions aren't shared across browsers.
  2. Session cookies are deleted when the browser session ends.
  3. If a cookie is received for an expired session, a new session is created that uses the same session cookie.
  4. Empty sessions aren't retained. The session must have at least one value set to persist the session across requests. When a session isn't retained, a new session ID is generated for each new request.
  5. The app retains a session for a limited time after the last request. The app either sets the session timeout or uses the default value of 20 minutes.
  6. Session data is deleted either when the ISession.Clear implementation is called or when the session expires.
  7. There's no default mechanism to inform app code that a client browser has been closed or when the session cookie is deleted or expired on the client.
  8. Session state cookies aren't marked essential by default. Session state isn't functional unless tracking is permitted by the site visitor. 
  9. Session state is ideal for storing user data that are specific to a particular session and where the data doesn't require permanent storage across sessions.



Enabling Session in ASP.Net Core:

The Microsoft.AspNetCore.Session package is included implicitly by the .Net Core Framework.  It provides middleware for managing session state.

In order to enable and use the session middleware, the ConfigureServices method of our Starup.cs file must contain the following:

  1. Any of the IDistributedCache memory caches. The IDistributedCache implementation is used as a backing store for sessions. 
  2. A call to AddSession() middleware
  3. A call to UseSession() middleware

We need to configure the session state before using it in our application. This can be done in the ConfigureServices() method in the Startup.cs class:

services.AddSession();



Then, we need to enable the session state in the Configure() method in the same class:

app.UseSession();

The “AddSession” method has one overload method, which accepts various session options such as Idle Timeout, Cookie Name, Cookie Domain, etc.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDistributedMemoryCache();
builder.Services.AddMvc();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});

app.UseRouting();
app.UseAuthorization();
app.UseSession();
app.MapRazorPages();
app.MapDefaultControllerRoute();

The order of middleware is important we should invoke the UseSession() before invoking UseMVC(). Call UseSession after UseRouting and before MapRazorPages and MapDefaultControllerRoute. HttpContext.Session is available after the session state is configured. HttpContext.Session can't be accessed before UseSession has been called.

The session state is non-locking. If two requests simultaneously attempt to modify the contents of a session, the last request overrides the first. The session is implemented as a coherent session, which means that all the contents are stored together. When two requests seek to modify different session values, the last request may override session changes made by the first.



The default session provider in ASP.NET Core loads session records from the underlying IDistributedCache backing store asynchronously only if the ISession.LoadAsync method is explicitly called before the TryGetValue, Set, or Remove methods. If LoadAsync isn't called first, the underlying session record is loaded synchronously, which can incur a performance penalty at scale.

The session uses a cookie to track and identify requests from a single browser. By default, this cookie is named AspNetCore.Session and it uses a path of /. Because the cookie default doesn't specify a domain, it isn't made available to the client-side script on the page (because HttpOnly defaults to true). 

Set and Get Session values:

Session state is accessed from a Razor Pages PageModel class or MVC Controller class with HttpContext.Session. This property is an ISession implementation.

 public void OnGet()
{
if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))
{
HttpContext.Session.SetString(SessionKeyName, "The Doctor");
HttpContext.Session.SetInt32(SessionKeyAge, 73);
}
var name = HttpContext.Session.GetString(SessionKeyName);
var age = HttpContext.Session.GetInt32(SessionKeyAge).ToString();

_logger.LogInformation("Session Name: {Name}", name);
_logger.LogInformation("Session Age: {Age}", age);
}



Q207. What is caching or response caching? How can you enable caching in ASP.Net Core?

Caching is an efficient way to store and retrieve data. The application can control the lifetime of cached items.  Cached data isn't associated with a specific request, user, or session. So do not cache user-specific data that may be retrieved by other user requests.

Caching significantly improves the performance of an application by reducing the number of calls to the actual data sources. It also improves scalability. Response caching is best suited for data that changes infrequently. Caching makes a copy of data and stores it instead of generating data from the original source.

Response caching reduces the number of requests a client or proxy makes to a web server. Response caching also reduces the amount of work the web server performs to generate a response. Response caching is set in headers. 

The ResponseCache attribute sets response caching headers. Clients and intermediate proxies should honor the headers for caching responses under the HTTP 1.1 Caching specification. Response caching headers control the response caching. ResponseCache attribute sets these caching headers with additional properties.



For server-side caching that follows the HTTP 1.1 Caching specification, use Response Caching Middleware. The middleware can use the ResponseCacheAttribute properties to influence server-side caching behavior.

builder.Services.AddResponseCaching();
builder.Services.AddControllers(options =>
{
options.CacheProfiles.Add("Default30",
new CacheProfile()
{
Duration = 30
});
});

app.UseCors();
app.UseResponseCaching();
app.UseAuthorization();
app.MapControllers();

The Response caching middleware enables caching server responses based on HTTP cache headers. Use Fiddler, Postman, or another tool that can explicitly set request headers. Setting headers explicitly is preferred for testing caching. The ResponseCacheAttribute specifies the parameters necessary for setting appropriate headers in response caching.



Q208. What is an In-Memory cache? How can you use the in-memory cache in ASP.NET Core?

ASP.NET Core supports several different caches. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the webserver. 

Apps running on a server farm (multiple servers) should ensure sessions are sticky when using the in-memory cache. Sticky sessions ensure that requests from a client all go to the same server. 

Non-sticky sessions in a web farm require a distributed cache to avoid cache consistency problems. The in-memory cache can store any object. The distributed cache interface is limited to byte[]. The in-memory and distributed cache-store cache items as key-value pairs.

You can enable the in-memory cache in the ConfigureServices method in the Startup class: 



public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  services.AddMemoryCache();
}

Using a shared memory cache from Dependency Injection and calling SetSize, Size, or SizeLimit to limit cache size can cause the app to fail. When a size limit is set on a cache, all entries must specify size when being added. When using SetSize, Size, or SizeLimit to limit cache, create a cache singleton for caching.

In-memory caching is a service that's referenced from an app using Dependency Injection. Request the IMemoryCache instance in the constructor.

public class IndexModel : PageModel
{
 private readonly IMemoryCache _memoryCache;
  public IndexModel(IMemoryCache memoryCache) =>  _memoryCache = memoryCache;



Q209. What is Cache busting? How Cache busting is handled in ASP.NETCore?

When your browser makes a request to the server to get a static file, after this file was downloaded, it will cache them to improve performance in the next request. This cached file can be stored for a very long time. 

If you have made changes in the file on the server-side and your client has this file in the cache browser, it will not see any changes due to this file will not be downloaded in the next request.

Cache busting solves this problem by adding a unique file identifier that tells the browser that this file has a new version on the server-side. So when the next request will be sent to the server, the browser will not using the old file from the cache but get the new version from the server.

In ASP.NET Core we can resolve this problem by using Link/Script Tag Helper with attribute asp-append-version set to true.

<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<script src="~/js/site.js" asp-append-version="true"></script>

If this attribute is set to true, a version query string is added to the link.



Q210. What is Query String?

We can pass a limited amount of data from one request to another by adding it to the query string of the new request. This is useful for capturing the state in a persistent manner and allows the sharing of links with the embedded state. As URL query strings are public, we should never use query strings for sensitive data.

Model binding maps data from HTTP requests to action method parameters. So if we provide the values for name and age as either form values, route values, or query strings, we can bind those to the parameters of our action method.

public IActionResult GetQueryString(string name, int age)
{
User newUser = new User()
{
Name = name,
Age = age
};
return View(newUser);
}

If you invoke the above method by passing query string parameters: /user/getquerystring?name=John&age=31 the query parameters will be mapped to the respective parameters.

In addition to unintended sharing, including data in query strings will make our application vulnerable to Cross-Site Request Forgery (CSRF) attacks, which can trick users into visiting malicious sites while authenticated.



Q211. What are Hidden Fields?

We can save data in hidden form fields and send it back in the next request. Sometimes we require some data to be stored on the client-side without displaying it on the page. Later when the user takes some action, we’ll need that data to be passed on to the server-side. 

In the View, we can create a hidden field and bind the Id value from the Model:

@Html.HiddenFor(model => model.Id)

Because the client can potentially tamper with the data, the app must always revalidate the data stored in hidden fields.




Q212. What is TempData?

ASP.NET Core exposes the TempData property which can be used to store data until it is read. TempData is implemented by TempData providers using either cookies or session state. We can use the Keep() and Peek() methods to examine the data without deletion. 

The cookie-based TempData provider is used by default to store TempData in cookies. The cookie data is encrypted using IDataProtector, encoded with Base64UrlTextEncoder, then chunked. The maximum cookie size is less than 4096 bytes due to encryption and chunking. 

TempData is particularly useful when we require the data for more than a single request. We can access them from controllers and views.

TempData["UserId"] = 101;
var userId = TempData["UserId"] ?? null; 

The TempData is available when we read it for the first time and then it loses its value. If we need to persist the value of TempData even after we read it then you have to use the keep and peak method.



var userId = TempData["UserId"]?.ToString();
TempData.Keep();
// OR
var userId = TempData.Peek("UserId")?.ToString();

The TempData.Keep() method retains the value corresponding to the key passed in TempData. If no key is passed, it retains all values in TempData.

TempData.Peek(string key) method gets the value of the passed key from TempData and retains it for the next request.



Q213. What are the different ways to pass data from controller to view in ASP.Net Core?

For passing data from the controller into the views, we can use two approaches: Strongly Typed Data and Weakly Typed Data.

Strongly Typed Data: In this approach, we pass a model from the controller into the view. 

return View(model);

The advantage of this method is that we get a strongly typed model to work within the view.

Weakly Typed Data: There are two approaches to passing a weakly typed data into the views - ViewData and ViewBag



ViewData is a dictionary object and we can get or set values using a key. ViewData exposes an instance of the ViewDataDictionary class.

 ViewData["UserId"] = 101;
 var userId = ViewData["UserId"]?.ToString();

ViewBag is similar to ViewData but it is a dynamic object and we can add data to it without converting it to a strongly typed object. In other words, ViewBag is just a dynamic wrapper around ViewData.

ViewBag.UserId = 101;
var userId = ViewBag.UserId;

The cookie-based TempData provider is enabled by default. To enable the session-based TempData provider, use the AddSessionStateTempDataProvider extension method. Only one call to AddSessionStateTempDataProvider is required:

builder.Services.AddRazorPages().AddSessionStateTempDataProvider();
builder.Services.AddControllersWithViews().AddSessionStateTempDataProvider();
builder.Services.AddSession();

app.UseSession();


To Be Continued Part-22...


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.