<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>asp net core 6 tips &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/asp-net-core-6-tips/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Tue, 25 Oct 2022 04:02:20 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>asp net core 6 tips &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Implement Cookies in ASP.NET Core 6</title>
		<link>https://topreviewhostingasp.net/how-to-implement-cookies-in-asp-net-core-6/</link>
					<comments>https://topreviewhostingasp.net/how-to-implement-cookies-in-asp-net-core-6/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Tue, 25 Oct 2022 04:00:38 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core 6]]></category>
		<category><![CDATA[asp net core 6 tips]]></category>
		<category><![CDATA[asp net core 6 tutorial]]></category>
		<category><![CDATA[asp net core cookie]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3246</guid>

					<description><![CDATA[The term cookie refers to a piece of data that is saved on the computer of a user and is generally used to record information about the user. Most browsers store each cookie as a small file, but Firefox stores them all in a single file. Cookies are made up of two parts: a key [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>The term <em>cookie</em> refers to a piece of data that is saved on the computer of a user and is generally used to record information about the user. Most browsers store each cookie as a small file, but Firefox stores them all in a single file. Cookies are made up of two parts: a <em>key</em> and a <em>value</em>.</p>



<p>ASP.NET 6 Core uses cookies to maintain user session state and for authentication purposes. ASP.NET Core uses the <strong>Microsoft.AspNetCore.Http.Cookie</strong> middleware to work with cookies. This middleware can be used to <strong>set</strong>, <strong>get</strong>, and <strong>delete</strong> cookies.</p>



<p>In this programming tutorial, we will be discussing cookies in ASP.NET 6 Core. We will cover what a cookie is, how to create and manipulate a cookie, and some of the security implications to keep in mind when working with cookies in ASP.NET.</p>



<h2 class="wp-block-heading">What is a Cookie in ASP.NET?</h2>



<p>In basic terms, a cookie is a smaller piece of information stored on a computer, usually as a text file. It keeps the information about you and your activities, like your preferred language or country. Cookies can also help web developers track user behaviour to improve our services and web sites.</p>



<p>To better understand this, consider the following example. If you have been performing searches for one particular type of product or service, but then start searching for something different, as a webmaster we might need to show more relevant search results to help get you closer to finding what you want.</p>



<p>Additionally, if you visit a website and add items to your shopping cart, but do not complete the purchase, the website will “remember” what you added to your cart so that when you come back later, your shopping cart will still contain those items.</p>



<p>Cookies allow web developers to customize content based on how people use our site — for example, by recognizing when they return after logging out of their account. This customization allows us to make better decisions and understand how visitors interact with our content to optimize future experiences accordingly.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.asphostportal.com" target="_blank" rel="noreferrer noopener"><img fetchpriority="high" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure></div>


<h3 class="wp-block-heading">What are the Different Types of Cookies?</h3>



<p>Basically, cookies can be divided into two types, namely <em>session</em> cookies and <em>persistent</em> cookies. When you visit a website, session cookies are stored on your computer only for the duration of your visit. A session cookie is destroyed when you leave your browser or move away from a web page.</p>



<p>As the name suggests, persistent cookies dwell on your computer even after you have closed your web browser. Persistent cookies can store information accessible across multiple sessions. Generally, these cookies store login information or preferences.</p>



<h2 class="wp-block-heading">How to Create a Cookie in ASP.NET</h2>



<p>Creating a cookie in ASP.NET Core is simple. First, create a new <strong>CookieOptions</strong> object as shown in the code example given below:</p>



<pre class="wp-block-preformatted">var cookieOptions = new CookieOptions(); </pre>



<p>Next, set the <em>expiration date</em> and <em>path</em> of the cookie, as shown below:</p>



<pre class="wp-block-preformatted">cookieOptions.Expires = DateTime.Now.AddDays(1);
cookieOptions.Path = "/"; </pre>



<p>Lastly, add the cookie to the <em>response object</em>, as shown below:</p>



<pre class="wp-block-preformatted">Response.Cookies.Append("SomeCookie", "SomeValue", cookieOptions);</pre>



<p>You can view your web browser’s cookie cache to determine whether a cookie has been written correctly.</p>



<h2 class="wp-block-heading">How to Read a Cookie in ASP.NET</h2>



<p>In ASP.NET 6 Core, you can take advantage of the <strong>Request</strong> object’s <strong>Cookies</strong> collection to read a cookie. This collection is an instance of the <strong>HttpCookieCollection</strong> class. To read a cookie, use the indexer of this class to retrieve the <strong>HttpCookie</strong> object for a given cookie name:</p>



<pre class="wp-block-preformatted">var cookie = Request.Cookies["cookieName"]; </pre>



<p>If the cookie does not exist, the indexer returns <strong>null</strong>. You can also use the <strong>Cookies</strong> collection’s <strong>Get</strong> method to retrieve a cookie:</p>



<pre class="wp-block-preformatted">var cookie = Request.Cookies.Get("cookieName"); </pre>



<p>If the cookie does not exist, this method returns <strong>null</strong> as well.</p>



<h2 class="wp-block-heading">How to Update a Cookie in ASP.NET</h2>



<p>To update a cookie in ASP.NET 6 Core, you will need to retrieve the cookie from the <strong>Request</strong> object using the following piece of code:</p>



<pre class="wp-block-preformatted">var cookie = Request.GetCookies("cookieName"); </pre>



<p>You can then modify the cookie value as desired. Lastly, you can write the updated cookie back to the <strong>Response</strong> object using the <strong>SetCookie</strong> method, as shown below:</p>



<pre class="wp-block-preformatted">Response.SetCookie(cookie);</pre>



<h2 class="wp-block-heading">Delete a Cookie in ASP.NET</h2>



<p>When using ASP.NET Core 6, there are two ways to delete a cookie. The first way is to use the <strong>Delete</strong> method of the <strong>Cookie</strong> object as shown below:</p>



<pre class="wp-block-preformatted">Response.Cookies.Delete(somekey); </pre>



<p>The second way is to use the <strong>Response</strong> object and set the <strong>Expires</strong> property of the cookie to a date in the past as shown in the ASP.NET code example below:</p>



<pre class="wp-block-preformatted">Response.Cookies["cookieName"].Expires = DateTime.Now.AddDays(-1);</pre>



<p>You can use the <strong>Clear</strong> method to clear all cookies as shown here:</p>



<pre class="wp-block-preformatted">Response.Cookies.Clear();</pre>



<h2 class="wp-block-heading">How to Access Cookies in the Controller Method</h2>



<p>To access cookies in the <strong>Controller</strong> method, developers should register an instance of type <strong>IHttpContextAccessor</strong> in the <strong>Program.cs</strong> file as shown below:</p>



<pre class="wp-block-preformatted">builder.Services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();</pre>



<p>To read or write cookie data in your controller methods, you will need to inject an instance of type <strong>IHttpContextAccessor</strong> in the constructor of your controller. The code example given below illustrates how this can be achieved:</p>



<pre class="wp-block-preformatted ">public class SomeController : Controller
{
  private readonly IHttpContextAccessor _httpContextAccessor;
  public SomeController(IHttpContextAccessor httpContextAccessor)
  {
     this._httpContextAccessor = httpContextAccessor;
  }   
  //Write your action methods here
}</pre>



<p>You can now use the following piece of code to access the <strong>Cookies</strong> object in your controller methods:</p>



<pre class="wp-block-preformatted">CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddSeconds(30);
_httpContextAccessor.HttpContext.Response.Cookies.Append("someKey", "someValue", options);</pre>



<h2 class="wp-block-heading">Final Thoughts on Cookies in ASP.NET</h2>



<p>If you would like to use cookies to store sensitive information, it is important to ensure that your cookies are properly secured using SSL/TLS encryption. In this web development tutorial, we examined how programmers can work with cookies in ASP.NET 6 Core. We also explored the different types of cookies and how to create, read, and update them programmatically.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-implement-cookies-in-asp-net-core-6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Use Entity Framework Connect to SQL Server</title>
		<link>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/</link>
					<comments>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 18 Mar 2022 07:44:06 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[.net core 6]]></category>
		<category><![CDATA[asp net core 6 tips]]></category>
		<category><![CDATA[asp net core 6 tutorial]]></category>
		<category><![CDATA[entity framework tips]]></category>
		<category><![CDATA[entity framework tutorial]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3013</guid>

					<description><![CDATA[This post shows goes through the steps to connect a .NET 6 API to SQL Server using Entity Framework Core, and automatically create/update the SQL Server database from code using EF Core migrations. We&#8217;ll start with an example .NET 6 CRUD API from a tutorial I posted recently, it uses the EF Core InMemory db [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>This post shows goes through the steps to connect a .NET 6 API to SQL Server using Entity Framework Core, and automatically create/update the SQL Server database from code using EF Core migrations.</p>



<p>We&#8217;ll start with an example .NET 6 CRUD API from a tutorial I posted recently, it uses the EF Core InMemory db provider by default for testing, we&#8217;ll update it to connect to a SQL Server database and run EF Core migrations to auto generate the database and tables from code. </p>



<h2 class="wp-block-heading">Requirements!</h2>



<p>To follow the steps in this tutorial you&#8217;ll need the following:</p>



<ul>
<li><a href="https://dotnet.microsoft.com/download" target="_blank" rel="noreferrer noopener">.NET SDK</a> &#8211; includes the .NET runtime and command line tools.</li>
<li><a href="https://code.visualstudio.com/" target="_blank" rel="noreferrer noopener">Visual Studio Code</a> &#8211; code editor that runs on Windows, Mac and Linux. If you have a different preferred code editor that&#8217;s fine too.</li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp" target="_blank" rel="noreferrer noopener">C# extension</a> for Visual Studio Code &#8211; adds support to VS Code for developing .NET applications.</li>
<li>SQL Server &#8211; you&#8217;ll need access to running SQL Server instance for the API to connect to, it can be remote (e.g. Azure, AWS etc) or on your local machine. The Express edition of SQL Server is available for free at <a href="https://www.microsoft.com/sql-server/sql-server-downloads" target="_blank" rel="noreferrer noopener">https://www.microsoft.com/sql-server/sql-server-downloads</a>.</li>
</ul>



<h2 class="wp-block-heading">Download &amp; Run the example .NET 6 API</h2>



<p>Follow these steps to download and run the .NET 6 CRUD API on your local machine with the default EF Core InMemory database:</p>



<ol>
<li>Download or clone the tutorial project code from <a href="https://github.com/cornflourblue/dotnet-6-crud-api" target="_blank" rel="noreferrer noopener">https://github.com/cornflourblue/dotnet-6-crud-api</a></li>
<li>Start the api by running <code>dotnet run</code> from the command line in the project root folder (where the WebApi.csproj file is located), you should see the message <code>Now listening on: http://localhost:4000</code>.</li>
<li>You can test the API directly with a tool such as <a href="https://www.postman.com/downloads" target="_blank" rel="noreferrer noopener">Postman</a>.</li>
</ol>



<h4 class="wp-block-heading">Starting in debug mode</h4>



<p>You can also start the application in debug mode in VS Code by opening the project root folder in VS Code and pressing F5 or by selecting Debug -&gt; Start Debugging from the top menu, running in debug mode allows you to attach breakpoints to pause execution and step through the application code.</p>



<h2 class="wp-block-heading">Update .NET 6 API to use SQL Server</h2>



<h4 class="wp-block-heading"><br />Add SQL Server database provider from NuGet</h4>



<p>Run the following command from the project root folder to install the EF Core database provider for SQL Server from NuGet:</p>



<pre class="wp-block-code"><code>dotnet add package Microsoft.EntityFrameworkCore.SqlServer</code></pre>



<h4 class="wp-block-heading">Add connection string to app settings</h4>



<p>Open the <code>appsettings.json</code> file and add the entry <code>"ConnectionStrings"</code> with a child entry for the SQL Server connection string (e.g. <code>"WebApiDatabase"</code>), the connection string should be in the format <code>"Data Source=[DB SERVER URL]; Initial Catalog=[DB NAME]; User Id=[USERNAME]; Password=[PASSWORD]"</code>, or to connect with the same account that is running the .NET API use the connection string format <code>"Data Source=[DB SERVER URL]; Initial Catalog=[DB NAME]; Integrated Security=true"</code>.</p>



<p>When EF Core migrations generates the database, the <code>Initial Catalog</code> value will be the name of the database created in SQL Server.</p>



<p>The updated <code>appsettings.json</code> file with the connection string should look something like this:</p>



<pre class="wp-block-code"><code>{
    "ConnectionStrings": {
        "WebApiDatabase": "Data Source=localhost; Initial Catalog=dotnet-6-crud-api; User Id=testUser; Password=testPass123"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    }
}</code></pre>



<h4 class="wp-block-heading">Update Data Context to Use SQL Server</h4>



<p>The <code>DataContext</code> class located at <code>/Helpers/DataContext.cs</code> is used for accessing application data through Entity Framework. It derives from the Entity Framework <code>DbContext</code> class and has a public <code>Users</code> property for accessing and managing user data.</p>



<p>Update the <code>OnConfiguring()</code> method to connect to SQL Server instead of an in memory database by replacing <code>options.UseInMemoryDatabase("TestDb");</code> with <code>options.UseSqlServer(Configuration.GetConnectionString("WebApiDatabase"));</code>.</p>



<p>The updated <code>DataContext</code> class should look like this:</p>



<pre class="wp-block-code"><code>namespace WebApi.Helpers;

using Microsoft.EntityFrameworkCore;
using WebApi.Entities;

public class DataContext : DbContext
{
    protected readonly IConfiguration Configuration;

    public DataContext(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        // connect to sql server with connection string from app settings
        options.UseSqlServer(Configuration.GetConnectionString("WebApiDatabase"));
    }

    public DbSet&lt;User&gt; Users { get; set; }
}</code></pre>



<h2 class="wp-block-heading">Create SQL Database from code with EF Core Migrations</h2>



<h4 class="wp-block-heading"><br />Install dotnet ef tools</h4>



<p>The .NET Entity Framework Core tools (<code>dotnet ef</code>) are used to generate EF Core migrations, to install the EF Core tools globally run <code>dotnet tool install -g dotnet-ef</code>, or to update run <code>dotnet tool update -g dotnet-ef</code>. For more info on EF Core tools see <a href="https://docs.microsoft.com/ef/core/cli/dotnet" target="_blank" rel="noreferrer noopener">https://docs.microsoft.com/ef/core/cli/dotnet</a></p>



<h4 class="wp-block-heading">Add EF Core Design package from NuGet</h4>



<p>Run the following command from the project root folder to install the EF Core design package, it provides cross-platform command line tooling support and is used to generate EF Core migrations:</p>



<pre class="wp-block-code"><code>dotnet add package Microsoft.EntityFrameworkCore.Design</code></pre>



<h4 class="wp-block-heading">Generate EF Core migrations</h4>



<p>Generate new EF Core migration files by running the command <code>dotnet ef migrations add InitialCreate</code> from the project root folder (where the WebApi.csproj file is located), these migrations will create the database and tables for the .NET Core API.</p>



<h4 class="wp-block-heading">Execute EF Core migrations</h4>



<p>Run the command <code>dotnet ef database update</code> from the project root folder to execute the EF Core migrations and create the database and tables in SQL Server.</p>



<p>Check SQL Server and you should now see your database with the tables <code>Users</code> and <code>__EFMigrationsHistory</code>.</p>



<h2 class="wp-block-heading">Restart .NET 6.0 CRUD API</h2>



<p>Stop and restart the API with the command <code>dotnet run</code> from the project root folder, you should see the message <code>Now listening on: http://localhost:4000</code> and the API should now be connected to SQL Server.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
