Tech Point Fundamentals

Sunday, January 29, 2023

C# Interview Questions and Answers List

C# Interview Questions and Answers List

csharp-interview-questions-list

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

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



Introduction


I have already posted all the C# Interview Questions and Answers article series. Here we will see the C# Interview Questions Summary and the particular part link so that you can walk through the answer to the particular interview question directly.

Please read the following important Interview Questions and Answers article series list here: 








 C# Interview Questions And Answers List 




Q001. What are the 4 pillars of OOPS?
Q002. What is the difference between Abstraction vs Encapsulation?
Q003. What is the difference between Class vs Structure in C#?
Q004. What are the different Access Modifiers in C#?
Q005. What is Polymorphism in C#? What are the different types of Polymorphism?
Q006. What are the different ways to implement Polymorphism in C#?
Q007. What is the difference between Early Binding vs Late Binding in C#? or What is the difference between Compile Time Polymorphism vs Run-Time Polymorphism in C#?
Q008. What is Shadowing in C#? or  What is the Method Hiding in C#? How can you achieve that?
Q009. What is the abstract method? How an abstract method is different from a virtual method?
Q010. What is the difference between Overloading vs Overriding in C#?







Q011. Can you achieve method overloading by inheritance? How?
Q012. Can you overload the main() method in C#? 
Q013. Can you achieve method overriding without inheritance, how?
Q014. What is the difference between Method Overriding vs Method Hiding?
Q015. We have two methods, one is returning IEnumerable results and the second one is void. Is it an example of Static Polymorphism?
Q016. What is Constructor Overloading in C#? Can you overload a static constructor in C#?
Q017. What is the difference between a virtual method vs abstract method?
Q018. What is the difference between inheritance vs composition? Why Composition is immune to Fragile Base Class Problem?
Q019. How can you achieve composition with the abstract classes? 
Q020. What happens if the inherited interfaces have conflicting method names? 







Q021. What is the Fragile Base Class Problem (FBCP) of OOPS? How can you avoid this problem? 
Q022. What is an abstract class? Can an abstract class implement an interface?
Q023. When do you choose interface over an abstract class or vice versa?
Q024. Can you define constructors in the abstract class? What is the use of a constructor in an abstract class that can not be instantiated?
Q025. Can you create the object of the abstract class? Is it mandatory to have abstract members in the abstract class?
Q026. What is the difference between abstract class vs interface?
Q027. Does C# support multiple inheritances? Why?
Q028. What is the Diamond Problem in OOPS?
Q029. What is the difference between class inheritance vs interface inheritance in C#?
Q030. What is the difference between multiple vs multilevel inheritances?







Q031. What is the order of constructor execution in the case of inheritance?
Q032. What is the order of static constructor execution in the case of inheritance?
Q033. Can two classes having different accessibility be inherited?
Q034. What is the static class? Can a static class implement interface, why?
Q035. What is the difference between a static class and an instance class having all members as static?
Q036. Can you inherit a class in a structure in C#?  Why?
Q037. What is the difference between structure vs class in C#?
Q038. Can you define a destructor in a structure? Why?
Q039. Can a structure have protected members? Why?
Q040. What is the difference between static class and instance class?







Q041. What is the difference between static class vs singleton?
Q042. What is the use of static class? Can you give me some real examples of static classes and static methods available in the .Net?
Q043. What is a partial class in C#? What is the use of partial class, do you have any real examples?
Q044. What is a partial method in C#? What is the use of partial methods?
Q045. Can you give me some real examples or use of partial classes and partial methods available in the .Net?
Q046. What is the difference between int vs Int32 in C#? 
Q047. What is the difference between string vs String? or What is the difference between string keyword and System.String class in C#?
Q048. What is the difference between String vs StringBuilder in C#?
Q049. What do you understand by the term 'TypeSafe'? Is C# a typesafe language?
Q050. What are Tuples in C#? What is its main use of it?







Q051. What is the difference between value type vs reference type?
Q052. What is the difference between reference type vs pass-by-reference?
Q053. What is the difference between OUT vs REF type parameters?
Q054. Can you pass a constant as a reference? Why?
Q055. If a method's return type is void, can you use a return statement in the method? What is the use of the return keyword?
Q056. What is a recursive method? Can you tell me any available recursive method names in C#?
Q057. In C# strings are the value type or reference type? How?
Q058. Enums are value type or a reference type in C#? 
Q059. In C#, the structure is a value type or a reference type?
Q060. What is the difference between casting vs conversion in C#?










Q061. What is the difference between boxing vs unboxing in C#?
Q062. What is the difference between boxing vs conversion in C#?
Q063. What is the difference between unboxing vs casting?
Q064. What is the difference between int.Parse(),  int.TryParse() and Convert.ToInt32() methods?
Q065. What is the difference between .ToString() and Convert.ToString() in C#?
Q066. What is the difference between String.IsNullOrEmpty() vs String.IsNullOrWhiteSpace() in C#?
Q067. What is a sealed class in C#? Can you make the abstract class sealed?
Q068. What is the sealed method in C#? How can you make any method sealed?
Q069. What is the difference between the sealed method vs the private method in C#?
Q070. What is the difference between Sealed Class vs Abstract Class in C#?








Q071. What is the difference between Sealed Class and Static Class in C#?
Q072. How a sealed class is different from a class having a private constructor in C#?
Q073. What is a destructor? How does it affect the garbage collection process? When should we define destructor in C#?
Q074. When the destructor is called? Can you pass parameters to destructors? How many destructors can be defined in a class?
Q075. What is garbage collection in C#? What are the different generations of GC? Why different GC Generations Required?
Q076. What is the difference between Destructor vs Finalizer in C#?
Q077. What is the difference between IDisposable and Finalizer? or What is the difference between dispose and finalize method in C#?
Q078. Can a static class contain a destructor? Why?
Q079. What is the purpose of using statement or using block in C#? or What is the using dispose pattern?
Q080. What is the use of the Checked and UnChecked keywords in C#?







Q081. What is the difference between constant vs readonly in C#?
Q082. What is recursion? Which data structure is used by the recursion?
Q083. What is a delegate in C#? Can you tell me some common delegates available in C#?
Q084. What is the use of FUNC, PREDICATE, and ACTION delegates in C#?
Q085. What are the generics in C#, and why they are required? How can you define a generic class and methods in C#?
Q086. What is the difference between System.Collections and System.Collections.Generic namespaces?
Q087. What is the difference between an Array vs ArrayList in C#?
Q088. What’s the difference between the Array.CopyTo vs Array.Clone or Copy vs Clone in C#?
Q089. What is an indexer in C#? What is the difference between indexer and property?
Q090. What is the difference between debug vs release mode?







Q091. What are the different ways to handle the exceptions in C#? Can a try block exist without a catch block in C#?
Q092. What is the difference between IEnumerable vs IEnumerator in C#?
Q093. What is the difference between IEnumerable vs IQueryable in C#?
Q094. What is the difference between IEnumerable vs IList vs List in C#?
Q095. What is the use of the Params keyword in C#?
Q096. What is the difference between Equality Operator "==" vs .Equals() method comparison in C#?
Q097. What is a private constructor? What is the use of a private constructor?
Q098. What is a static constructor in C#? How can you call the static constructor?
Q099. What is the Constructor Chaining in C#? How it is different from Constructor Overloading?
Q100. Can you prevent a class from being instantiated? What are the different ways to do that?







Q101 What is Data Annotation in C#? How can you do remote validation using it?
Q102. What is Reflection? What is the use of reflection in C#?
Q103. What is LINQ in C#?
Q104. What is Extension Method in C#? What is the difference between the Extension Method vs Overloaded Method vs Overridden Method?
Q105. What are Anonymous Types in C#? How it is different from dynamic types?
Q106. What is the difference between dynamic vs var type in C#?
Q107. What is the difference between the “throw” vs “throw ex” in .NET?
Q108. What is finally block? How many finally blocks can you define with a try block?
Q109. What will happen if the finally block throws an exception?
Q110. What is the difference between the IS vs AS Operators in C#?








Q121. What is the difference between Final, Finally, and Finalize?
Q122. What is the difference between First() vs FirstOrDefualt() in C#? What is the difference between First() vs Single()?
Q123. What is the volatile keyword? What is the use of volatile keywords in C#?
Q124. What is the difference between Deferred Execution vs Immediate Execution? or What is the difference between Lazy Operators vs Greedy Operators?
Q125. What is the difference between Lazy Loading vs Early Loading in C#? 
Q126. What is the difference between Late Binding vs Lazy Loading? Are both the same? 
Q127. What is the difference between Early Binding vs Early Loading? Are both the same?
Q128. What is the difference between "this" vs "base" keyword in C#?
Q129. What is the difference between foreach vs for loop in C#?
Q130. What is the difference between instance field vs property in the C# class?







Q131. What is TPL in the .Net? Why TPL is required in C#?
Q132. What is the difference between ForEach vs Parallel.ForEach loop in C#?
Q133. What is the difference between Standard For Loop vs Parallel.For Loop in C#?
Q134. What is the difference between task vs  process vs thread?
Q135. What is Multi-threading? What is the difference between Multi-threading vs MultiTasking and Multi-threading vs Concurrency?
Q136. What is the difference between Concurrency vs Parallelism? Are they same as async programming?
Q137. What is asynchronous programming? What is the use of async and await keywords in C#? 
Q138. What is a Task in C#? What is the difference between task vs thread?
Q139. What is synchronization and why it is important?
Q140. What is the difference between Join vs Lock synchronization?







Q141. What is the difference between Mutex vs Monitor?
Q142. What is Semaphore C#? How does the Semaphore work?
Q143. What is deadlock? How can you prevent deadlock in C#?
Q144. What do you mean by thread-safe? How can you share data between multiple threads?
Q145. How can you retrieve data from a thread? What is a callback method?
Q146. What is Anonymous Method in C#?
Q147. What is Lambda Expression in C#?
Q148. What is a thread? What is the thread life cycle or different states of a thread?
Q149. What is the difference between task.wait() vs  task.delay() vs thread.sleep() in C#?
Q150. What is string interpolation in C#?








Q151. What is the difference between generic vs non-generic collections? Why do we need generic collections?
Q152. What is ArrayList? What is the difference between Array vs ArrayList?
Q153. What is Dictionary? What is the difference between a List vs Dictionary?
Q154. What is HashTable? What is the difference between HashTable vs Dictionary?
Q155. What is Stack? What are the applications of Stack? What is the difference between Peek() vs Pop() operations?
Q156. What is Queue? What are the applications of Queue? What is the difference between Dequeue() vs Peek() operation?
Q157. What is Heap? What are the applications of Heap?
Q158. What is Linked List in C#? 
Q159. What is the difference between class vs object? 
Q160. What is the use of optional parameters? Can you overload two methods based on optional Parameters? 








Recommended Articles






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

    

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.