How To Using Sessions and HttpContext in ASP.NET Core and MVC Core

How To Using Sessions and HttpContext in ASP.NET Core and MVC Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET core 1.0 hosting. If you’re new to ASP.NET Core or MVC Core, you’ll find that sessions don’t work the way they used to. Here’s how to get up and running the new way.

Add Session NuGet Package

Add the Microsoft.AspNetCore.Session NuGet package to your project.

VERSION WARNING: As you’ll find with most Microsoft.* packages, you should make sure the versions all match. At RTM time as of writing, this means “1.0.0”.

Update startup.cs

Now that we have the Session nuget package installed, we can add sessions to the ASP.NET Core pipeline.

Open up startup.cs and add the AddSession() and AddDistributedMemoryCache() lines to the ConfigureServices(IServiceCollection services)

Next, we’ll tell ASP.NET Core to use a Memory Cache to store the session data. Add the UseSession() call below to the Configure(IApplicationBulider app, ...)

Where’s the Session variable gone?

Relax it’s still there, just not where you think it is. You can now find the session object by using HttpContext.Session. HttpContext is just the current HttpContext exposed to you by the Controller class.

If you’re not in a controller, you can still access the HttpContext by injecting IHttpContextAccessor.

Let’s go ahead and add sessions to our Home Controller:

You’ll see the Index() and About() methods making use of the Session object. It’s pretty easy here, just use one of the Set() methods to store your data and one of the Get() methods to retrieve it.

Just for fun, let’s inject the context into a random class:

Let’s break this down.

Firstly I’m setting up a private variable to hold the HttpContextAccessor. This is the way you get the HttpContext now.

Next I’m adding a convenience variable as a shortcut directly to the session. Notice the =>? That means we’re using an expression body, aka a shortcut to writing a one liner method that returns something.

Moving to the contructor you can see that I’m injecting the IHttpContextAccessor and assigning it to my private variable. If you’re not sure about this whole dependency injection thing, don’t worry, it’s not hard to get the hang of (especially constructor injection like I’m using here) and it will improve your code by forcing you to write it in a modular way.

But wait a minute, how do I store a complex object?

How do I store a complex object?

I’ve got you covered here too. Here’s a quick JSON storage extension to let you store complex objects nice and simple

Now you can store your complex objects like so:

and retrieve them just as easily:

Use a Redis or SQL Server Cache instead

Instead of using services.AddDistributedMemoryCache() which implements the default in-memory cache, you can use either of the following.

SQL Server
Firstly, install this nuget package:

  • "Microsoft.Extensions.Caching.SqlServer": "1.0.0"

Secondly, add the appropriate code snippet below:

Redis Cache
Unfortunately, the redis package does not support netcoreapp1.0 at the moment. You can still use this if you’re using net451 or higher.

"Microsoft.Extensions.Caching.Redis": "1.0.0"

Stay up to date

Even though we’ve reached RTM, you should still keep an eye on the ASP.NET Session Repository for any changes.

Cheap Drupal Hosting SEO Tips To Rank Better On Google

Cheap Drupal Hosting SEO Tips To Rank Better On Google

CheapASPNETHostingReview.com | Cheap and reliable Drupal hosting. This is a post about Drupal, SEO, and Drupal & SEO. While some of this information is specific to Drupal, other parts are just general to SEO, but what makes the general parts related to Drupal is that, in most cases, Drupal development makes it much easier to implement search engine optimization when compared to similar content management systems I have used.

1. Keyword Research is a MUST

Know what keywords you should be using throughout your copy, in your title tags, URLs, meta tags, meta description, alt tags, internal links, and headers. The best way to do that is to use Google’s Keyword Tool, now Keyword Planner. Using the keyword planner you can see how frequently terms are being search per month (globally and locally), how competitive they are for ranking, and how much they cost to advertise on. Better still, the keyword planner will give you related keywords to what you typed in. This tool is a must to start with for good Drupal SEO, really any SEO for that matter.

2. Google Analytics & Google Webmaster Tools

Get these two tools, Google Analytics & Webmaster Tools hooked up and running data on your Drupal site ASAP, and better still, get them hooked up together. If you aren’t pulling this data from your website you’re going to be lost in terms of what is currently going on, creating difficulty in making confident decisions on what to do next when it comes to SEO. There are a bunch of tools out there that offer similar insight when it comes to this information, but if you want to know what Google is seeing when it comes to your site, why not go directly to the horse’s mouth.

3. Key Drupal SEO Modules To Get Installed

Drupal has several modules that every site should install. That is, if you’re looking to take advantage of what Drupal already has to offer, and if you care to get found online ‘organically’ through someone typing words other than your company’s name.

  • Alinks: Creates automatic links allowing users to associate defined text to links.
  • Content Optimizer: Helps to ensure content conforms to Drupal SEO best practices and provides analysis pages to ensure SEO best practices are followed.
  • Custom Breadcrumbs: Allows you to set up parametrized breadcrumb trails for any node type.
  • Global Redirect: After turning on clean URLs and Pathauto, it fixes some of the more common URL problems.
  • Google Analytics: Visitor tracking.
  • HTML Purifier: Fixes substandard HTML on content generated by users.
  • Link Checker: Checks for broken links.
  • Menu Attributes: Additional attribute specification for menu items such as id, name, class, style, and rel.
  • Metatag: Enables full control of meta tags on your site, nodes, categories, views, etc.
  • Mollom: Spam protection.
  • Page Title: Allows the page title to be set.
  • Pathauto: Based on the title of the page, this module autocreates an SEO-friendly URL.
  • Path Redirect: Creates proper redirects for URLs.
  • Read More Link: Creates customized, SEO-friendly read more links.
  • SEO Checklist: Checklist that provides admin shortcuts and download links to pretty much all the modules and tasks to perform SEO on a Drupal site.
  • SEO Compliance Checker: Checks for on page SEO compliance giving the user analysis when a node is saved or previewed.
  • Scheduler: Allows scheduling for the publishing of nodes.
  • Site Map: Creates a plain text version of the sitemap.
  • Site Verification: Verification assistance of site ownership for search engines.
  • Syndication: Centralization, through a web page, all RSS feeds generated by Drupal.
  • Taxonomy Title: Title setting for taxonomy pages.
  • URL List: Lists every URL on your Drupal-based website by creating a plain text sitemap.
  • XML Sitemap: Creates search engine readable, dynamic sitemap that is Sitemaps.org compliant.

4. Backlinks, Backlinks, Backlinks

9shutterstock_125340119

Don’t let Google fool you, even with the Penguin and Panda updates, backlinks still count pretty big. What those updates are trying to do is get rid of all the big time comment spam and professional profile builders out there by penalizing sites with an overwhelming amount of those types of links.

The key to backlink building is to make it look natural, by having a good mix of links built with just plain URLs, home page URLs, keyword anchor text, long tail keyword phrases and use of “similar” keyword type phrases. Go after links from sites of all Page Rank types and make sure the links reference not only your home page but also your inner pages. Don’t sweat the no-follow links to your site, because here is the thing: they are still links and get counted, maybe not as much as a followed link, but they are still getting picked up.

Go for credible links, and look at that this way: Appnovation is a Drupal development company so we would definitely want to get a link from Drupal.org pointing back out our site because that is basically telling Google that Drupal.org (the foremost authority on Drupal) considers Appnovation a Drupal development company.

Talking about backlinks can go on and on, but the keys are:

  • continuously do it;
  • make it look natural;
  • keep it as credible is possible; and,
  • have the links touch as many different parts of your site as you can.

5. Watch Your Competitors

Unless you have monopoly, you are going to have to keep up with the competition. Keep an eye on what they are doing both on-page and off, as well as monitor what they are ranking for and where they are ranking. Competitors can give you great ideas on what you should be doing on your pages to make sure your rank is improving.

6. Continuously Update

Sites can’t just be a static page that you build and push live to just sit there. Today you have to continuously create content for it. Although not just new web page after new web page, but content of all types like case studies, product reviews, client testimonials, whitepapers, eBooks, infographics, demos, portfolios, videos, communities, blogs, social sections, and so on. Keep you site as dynamic as possible and keep giving Google a reason to come back and crawl you to see what’s going on. Refresh your website with a complete redesign from time to time so that you can add more ways for people interact with it. Basically today’s websites have to be living, breathing entities that need consistent feeding and constant attention. Drupal is an ideal content management system (CMS) for this very purpose.

7. Make It Work Together

The key to all of it is being able to make it work together: the keywords, the tracking, the modules, the backlinks, the competitive research, and the continuous updating. Leaving out any of those is going put a pretty big dent in comprehensive Drupal SEO strategy. Each item above requires the other 6 to be involved, or at least taken into account, someway, somehow.

Bonus. A Word of Caution

Word to the wise: don’t ever put all your eggs in the SEO basket. Not too many people know what makes up the Google algorithm (I am guessing you probably don’t) let alone when Matt Cutts’ team (I am also guessing you don’t know Matt Cutts or anyone on his team either) is going to make another change that could affect what your site shows up for, or where, in the rankings.