Merhaba, siteme hoşgeldiniz.

Paylaşımları kaçırmamak için bültene kayıt olmayı unutmayın.

Çarşamba, 08 Mart 2017 / Published in Uncategorized

Recently, when looking at how to configure authentication using external login providers (e.g. Google, Facebook) with ASP.NET Core I noticed that https is now a requirement for some of them.

Another thing I noticed was how hard it was to find resources about enabling HTTPS on ASP.NET Core.

This blog post is about the process of creating a local ASP.NET Core website running with HTTPS with no errors in Chrome (showing the green padlock in the address bar) for your local development time. And then how you can use Nginx or IIS when you are ready to expose it to the world.

In order to use HTTPS we need a digital certificate. If you need to generate your own to use at development time I recommend Using OpenSSL to Create Certificates. It not only explains how you can create your own certificate authority and certificates, but also how you can configure your browser (Chrome or Firefox) to trust the certificate authority.

Also, if you want to understand what’s the role of certificates in HTTPS, then have a look at Brief(ish) explanation of how https works.

From now on I’m assuming that you have generated your certificate authority, certificate and corresponding private key and you have a .pfx (Personal Information Exchange) file.

Create a new project

I’ll be describing the process using Visual Studio Code and Yeoman.

If you are not familiar with yeoman, it’s a command line tool that allows you to create new projects from a list of project templates. The yeoman generator (that’s the name of the package for yeoman that contains the templates) we are going to use is generator-aspnet. To install yeoman you first need npm and then you can follow the instructions for installing yeoman and the ASP.NET Core templates here.

The reason for using Visual Studio Code and yeoman is that this process works on Windows, Linux and macOS.

To use yeoman with the ASP.NET Core templates run the following command:

$ yo aspnet

    _-----_     ╭──────────────────────────╮
    |       |    │      Welcome to the      │
    |--(o)--|    │  marvellous ASP.NET Core │
`---------´   │        generator!        │
    ( _´U`_ )    ╰──────────────────────────╯
    /___A___\   /
    |  ~  |     
´   `  |° ´ Y ` 

? What type of application do you want to create? (Use arrow keys)
❯ Empty Web Application 
Empty Web Application (F#) 
Console Application 
Console Application (F#) 
Web Application 
Web Application Basic [without Membership and Authorization] 
Web Application Basic [without Membership and Authorization] (F#) 

Select Empty Web Application. A simple web project will be created that just has page with the text “Hello World”.

If you are running Windows and have the full version of Visual Studio you can just do File -> New Project, select .Net Core, ASP.NET Core Web Application and then select Empty.

Configuring HTTPS for Kestrel

Kestrel is the web server that is used by default with ASP.NET Core.

To add HTTPS support to Kestrel add the Microsoft.AspNetCore.Server.Kestrel.Https package as a dependency.

If you are using project.json you can do this by editing project.json’s “dependencies” section and adding:

"Microsoft.AspNetCore.Server.Kestrel.Https": "1.1.0"

The version number might be different for you, however it should be the same as the one used in the Microsoft.AspNetCore.Server.Kestrel package.

If you are using .csproj you can add the dependency by running:

dotnet add package Microsoft.AspNetCore.Server.Kestrel.Https

Certificate Configuration

To configure Kestrel to use our .pfx file (certificate and private key) we need to edit Program.cs where the WebHostBuilder is being created and make a few changes:

var host = new WebHostBuilder()
    .UseKestrel(options => {
        options.UseHttps("localhost.pfx", "password");

The changes are:

.UseKestrel(options => {
    options.UseHttps("localhost.pfx", "password");

Which is where we specify what is the .pfx file that we want to use and its password. UseHttps is an extension method, if you get an error saying it does not exist it’s because you didn’t add the Microsoft.AspNetCore.Server.Kestrel.Https nuget package, which is where it lives.



Which defines where Kestrel will be listening for incoming connections. Alternatively you could use https://localhost:4430 instead of *. With * however, you can use any domain name, for example if you have this web application in it would still work, whereas with localhost, only requests to localhost would be served.

In case you are wondering why I did not use the default HTTPS port, 443, that’s because you need special permissions on Linux for ports below 1024. In Windows this would not be a problem. However, because doing this with Kestrel is only recommended when you are at development time, it’s not a big problem.

If you are trying this in Linux, macOS or using the command line in Windows you can call dotnet run, open Chrome and go to https://localhost:43000 and see a green padlock icon.

If you are using full Visual Studio in Windows the way to do this is to specify that you want to run the web application directly and not through IIS Express:

Also select the browser you want to try it on. If you installed your test root certificate authority’s certificate in a specific browser, use that browser, for example Chrome (if you are confused by this statement I recommend that you read Brief(ish) explanation of how https works and Using OpenSSL to Create Certificates):

Finally, edit the project properties(right click and select properties):

And change the launch url:

Using ASP.NET Core with a reverse proxy

Although it is certainly possible to serve a web application using ASP.NET Core using only Kestrel, it is not recommended. This is because Kestrel is not a fully featured web server and is still lacking some security features.

Even though it is not recommended, you might just want to show something you’ve done to someone and skip the part of installing and configuring a web server. With services like DigitalOcean or Linode you can create a VPS in very little time and just have your ASP.NET Core available through there only having to install .net core.

However, if you want something more serious (and you probably do since you are here because of enabling HTTPS) you should use a full featured web server, like Nginx or IIS (in Windows), as a reverse proxy to your ASP.NET Core application.

A reverse proxy server is a web server that accepts requests and sends them to another web server which actually creates the responses for those requests. The responses are sent back to the proxy server who forwards them to the clients who issued the corresponding requests.

With Nginx acting as a reverse proxy it would look something like this:

Browser <----> Nginx <----> Kestrel

The good thing about this setup is that we can take advantage of Nginx (or IIS) being a full web server and enable HTTPS on it:

Browser <---- HTTPS ---> Nginx <---- HTTP ----> Kestrel

So we don’t even need to configure Kestrel with HTTPS, just Nginx.

Configuring HTTPS with Nginx

First you have to install Nginx. I’m using Ubuntu 16.04 for this, however you can even install it on Windows.

If you are running Ubuntu open a terminal and type

$ sudo apt-get install nginx

Next thing we need to do is to edit Nginx’s configuration. But before we do that it is useful to know what is the location of the configuration files and how they become enabled. The folder where the configuration files are usually placed is /etc/nginx/sites-available/ (this location might be different if you are using a different Linux distribution).

The configuration file that is present when you install Nginx is named default.

For a Nginx configuration to become enabled it must be located in the folder /etc/nginx/sites-enabled. So after creating a new configuration file (in sites-available) a symbolic link is created in sites-enabled that points to the new file.

Imagine we had just created a new configuration file named my-site-https in sites-available. After that you would go to sites-enabled folder and run the following command to create a symbolic link:

$ ln -s /etc/nginx/sites-available/my-site-htts

To make Nginx read this new configuration run the command:

$ sudo nginx -s reload

Now that we know how to create and enable Nginx configurations let’s create the configuration file for setting up Nginx as a reverse proxy to an ASP.NET Core application that is running at http://localhost:5000.

First create a new file in /etc/nginx/sites-available named, for example, aspnetcore, with the following contents:

server {
    listen 443 ssl;    
    ssl_certificate_key PATH_TO_PRIVATE_KEY/PRIVATE_KEY.pem;

    location / {
        proxy_pass http://localhost:5000;

Here we are configuring Nginx to listen to port 443 using SSL (443 is the default for HTTPS). Next we are specifying where the certificate (ssl_certificate) and private key (ssl_certificate_key) are located and finally we are instructing Nginx to forward all requests (location / will match all requests) to http://localhost:5000.

Finally, create the symbolic link to this file in sites-enabled (you can delete the link to the default file, this won’t delete the original file since it’s a symbolic link).

/etc/nginx/sites-enabled$ sudo ln -s /etc/nginx/sites-available/aspnetcore

To make Nginx load this configuration:

$ sudo nginx -s reload

If you have your ASP.NET Core application running at http://localhost:5000 you should now be able to open https://localhost and see it being served over HTTPS.

There’s a common issue that might happen when you reload the Nginx configuration, which is you get prompted for a password. Specifically for private key’s password. This might not be practical for you, so if you want to remove the password from the private key you can run the following command:

$ openssl rsa -in privateKeyWithPassword.pem -out privateKeyWithoutPassword.pem

Another useful thing you can do with Nginx is to have all requests to HTTP be redirected to HTTPS. If you want to enable this add this extra configuration to you aspnetcore Nginx configuration file:

server {
    listen 80;
    return 301 https://$host$request_uri;

Configuring Supervisor

One thing we must concern ourselves with is that we need to keep our ASP.NET Core web application running.

There’s a tool called supervisor that allows us to configure that an application should be initiated at startup time, and if it crashes it should be brought back up

First thing we need to do is install it. I’m using Ubuntu 16.04 for this, and in this distribution installing it is very simple:

$ sudo apt-get install supervisor

Next thing we need to do is to create a supervisor configuration file for our web application. Let’s call it aspnetcore.conf and add it to /etc/supervisor/conf.d (you need to do this using sudo):

Place this inside the configuration file:


The first line defines the name (aspnetcore) by which we can refer to the web application in supervisor.

The line with command defines the command to run. In this case it’s dotnet followed by your web application’s dll. This is equivalent to running dotnet run in the root of your project.

The next line (directory=) sets the working directory as the one where your project is located.

autostart=true means that the application will be started at startup time.

autorestart=true means that the application will be restarted if it crashes or even if it is stopped (for example using kill). If you want your application to only be restarted in case of a crash change it to autorestart=unexpected.

The next two lines define to which files the standard and error output are written to, respectively.

Finally environment allows us to set environment variables, in this case we are setting ASPNETCORE_ENVIRONMENT=Production.

To enable this new configuration file run the following commands:

$ sudo supervisorctl reread
$ sudo supervisorctl update

You can check the status of the processes running under supervisor by running

$ sudo supervisorctl

It should display something similar to:

aspnetcore RUNNING pid 18817, uptime 0:05:29 supervisor>

There are more several commands you can use to manage the processes under supervisor, type help for a list of the available commands. To quit, just type quit.

Configuring HTTPS with IIS

The first step in enabling HTTPS while using IIS is to install our certificate and private key (using a .pfx file that contains both).

Open IIS Manager and select Server Certificates

Click import certificate:

Select the .pfx file and enter the corresponding password, leave the store as Personal:

Before we continue it is important to mention that you need to have the ASP.NET Core Module installed. It is very likely that you already do since it is installed for you when you install the .Net Core SDK.

However, in case it is not (you can verify it in IIS Manager by opening Modules and check if AspNetCoreModule is listed there), you can find installation instructions here and a direct link for the downloading the ASP.NET Core Server Hosting Bundle here.

What this module does is to start your ASP.NET Core website and keep it running (restarting it if it crashes). This module is also responsible for forwarding the HTTP requests to your web app and then forward the responses back to the client.

An important thing to know about the AspNetCoreModule is that it is configured by the web.config file in the root of your project. You need to run dotnet publish on your project to get web.config setup properly in your publish folder.

The next step is to create a new Application Pool and select No Managed Code as the .NET CLR Version. Normally the websites run inside a IIS worker process, but in .NET Core they run as a separate process, so there’s no need for a .Net Runtime in the app pool:

Finally, let’s create a new website inside IIS for our ASP.NET Core application. We need to select the app pool we have just created, select as the Physical Path the path to the published website, select HTTPS as the binding and our certificate in the SSL certificate dropdown:

You should now be able to use https to browse to your ASP.NET Core app.


Çarşamba, 08 Mart 2017 / Published in Uncategorized

We are pleased to announce updates to our ASP.NET tools, ASP.NET Core tools, Container tools, and frameworks that are shipping as part of the Visual Studio 2017 release today.  We have made significant updates to the web development tools to make them easier for you to use and help make you more productive in your daily web development tasks.

ASP.NET Core Tooling

As part of this release, we are including an RTM version of the ASP.NET Core tools.  Visual Studio 2015 included preview tooling based on project.json that supported the 1.0 and 1.1 versions of the ASP.NET Core framework. Visual Studio 2017 and it’s .csproj tooling is the tooling for ASP.NET Core moving forward. Customers should plan to migrate their applications to the new .csproj tooling.

With Visual Studio 2017, we have delivered updates that complete the experience for ASP.NET Core developers.  ASP.NET Core is available in the Web and .NET Core sections of new projects:

File – New – Project


The new ASP.NET Core project template screen has some minor updates, and still makes available the choice of three web templates: Empty, API, and Web Application

New Project Template

You can now choose to use ASP.NET Core 1.0 or 1.1 using the combo-box at the top of the screen.  Additionally, you can choose to add Container support to your project with the checkbox at the bottom-left of the screen.  This option adds:

  • Docker files to your project for building Container images
  • a Docker Compose project to define how you instance your Containers
  • Multi-project/container debugging support for Containers.

Default Web Application Project Structure

We are now shipping templates with the following features:

  • Bower enabled by default, delivering the bootstrap, jQuery, and jQuery validation libraries and added to the wwwroot/lib folder by default.
  • We removed the package.json file for npm integration
  • We removed gulpfile.js file for JavaScript task processing.

Existing projects using npm, grunt, or gulp will continue to enjoy the features we added for those frameworks, including the npm package management experience and the Task Runner Explorer. npm, Gulp, and Grunt features can still be added and enabled on new projects.  We now ship with a bundleconfig.json that activates the simplified resource bundler.  More information about configuring the bundler can be found on the extension’s GitHub wiki.

.NET Core csproj Support

Starting with Visual Studio 2017 and the .NET Core SDK 1.0 release, we exclusively support the updated MSBuild file format.  If you have an older project that uses the project.json format, it will be converted to the new format the first time you open it with Visual Studio 2017.

In the csproj project file for your project you will notice a dramatic simplification of the project references.

In particular, the project file now has the following features activated by default:

  • An “Sdk” attribute on the Project root-element that is set to “Microsoft.NET.Sdk.Web”. This instructs the project system to manage this project with tooling to support an ASP.NET Core project that delivers a web endpoint with appropriate defaults.
  • A collection of “PackageReference” elements. These items are NuGet packages that should be installed and referenced by our project.  The packages.config file is no longer needed.
  • A collection of “DotNetCliToolReference” elements. These items enhance the dotnet command-line tool to give it features necessary to build and manage this project.  In the sample above, it enables the Entity Framework tools and the User Secret manager.

New DotNet New Templates

The dotnet command-line tool has new templates for the creation of new .NET Core projects.  When you run “dotnet new” now, you will see a selection of templates that you can choose from:

dotnet new templates

This now makes it very easy to understand the project templates that are available, and the languages that are supported for each.  Additionally, it is very easy to create your own templates or download other templates to use.  Instructions for building your own templates are on the project templates wiki.  An in-depth walk-through of the dotnet new experience can be found on the .NET Blog.

Debug Your Applications with Google Chrome

Visual Studio has supported client-side JavaScript debugging with Internet Explorer for a long time.  With Visual Studio 2017, you can now add the Google Chrome browser to the list of supported client-side debuggers.  If you use Google Chrome as your browser at Debug time, you will be able to hit breakpoints and step through the JavaScript and TypeScript code executing in the browser.  More details about this feature are in the client-side debugging announcement blog post.

Container Tooling Updates

Containers are now easier than ever to use with your projects in Visual Studio 2017.  For your ASP.NET Core projects, you can choose to add Docker container support at project creation time, and you can also add Docker support to your existing projects by right-clicking on the project in the Solution Explorer and choosing the Add – Docker Support menu option.

To make it easier to work with single and multiple projects, we moved the docker-compose configuration to a separate project in your solution explorer.

Docker Compose Project

If you want to debug your project inside of the container, set the docker-compose project as the startup project.  You can still set your project as the startup project and debug on your local machine without effecting any containers.

Since we are using a standard docker-compose file, you are free to add other containers into the mix that should be launched when you debug your solution.  Add your favorite database, load-balancer, or other service images into your docker-compose to allow you to work with those resources while you debug your ASP.NET application. Those additional containers may be written in other languages, but you can still instance them during your debugging session.

When compiling your code, you can now build your solution directly in a Docker container, representing how your build system can compile your code. Running the following code will volume mount your solution, execute “dotnet restore” and “dotnet publish” in the container, generating the compiled output to place in your optimized Docker images.

docker-compose -f up

ASP.NET with Windows Container Support

We didn’t limit our support for Docker containers to only the ASP.NET Core projects, we’ve added support for ASP.NET (.NET Framework) applications as well.  You can use the same commands to add Windows container support to your favorite ASP.NET Web Forms, MVC, or Web API projects easily.  These applications will launch and run inside of a Windows container that is configured with IIS and the latest version of the .NET Framework.

Before you can run .NET Framework in Windows Containers locally, make sure that you have the latest version of Docker for Windows and that you have switched to Windows Containers using the Docker systray icon.

Publish Your Application

When it comes time to publish your application, you will find a greatly improved experience when you choose the Publish action on your project.

Publish Your Project

You can now choose to publish to the following locations:

  • Azure App Service, including Linux Container Deployments (if Docker is enabled for your ASP.NET Core project)
  • IIS, FTP
  • A folder
  • An Azure Virtual Machine

If you have your application configured with Docker support, the publish option will allow you to publish your application as a container to your own Azure Container Registry and deploy to Azure App Service Linux using containers.

Options for Publication to Azure App Service

Publishing to your own container registry makes it easier for you to re-use your container to deploy new versions or more instances easily.

Recommended Visual Studio Extensions

There are two extensions that we recommend adding to your Visual Studio 2017 installation to assist with ASP.NET Core application development:

  • The Project File Tools extension provides intellisense for NuGet packages when hand-editing a csproj file
  • The Razor Language Service provides intellisense, syntax highlighting, and tooltip support for ASP.NET Core Razor Tag Helpers in Visual Studio 2017

To learn more about ASP.NET Core and Razor Tag Helpers, see the Intoduction to Tag Helpers in ASP.NET Core on the website. To create your own custom Tag Helpers, see Introduction to Authoring Tag Helpers in ASP.NET Core.

Additionally, the new Web Essentials 2017 extension pack includes both of these extensions and a number of other helpful tools for any web developer.


Visual Studio 2017 is here and has the tools you need to be an effective web developer with ASP.NET, ASP.NET Core, and Docker container support.  Visual Studio Community is available for free to hobbyists and small companies with limitations, download a copy and get started being a more productive web developer today.

Salı, 07 Mart 2017 / Published in Uncategorized

Web Service still plays a very important role in today’s applications in order to share information. Two or three years ago, I wrote a series of articles on ASP.NET Web Services, which was very popular, and due the this people were asking me to write an article on consumning Web Services in MVC Applications in my own simple words. So based on that requirment, I have decided to write about consuming Web Service in ASP.NET MVC article . In this article, we will learn how to consume Web Services in ASP.NET MVC applications.

If you are new to ASP.NET Web Services, then please folllow my previous videos and articles on ASP.NET Web Services, using the links given below.

I hope, you have referred to the preceding articles. Now, let’s create a simple ASP.NET MVC application to demonstrate this requirment .

 Step 1


Create MVC Application

  1. "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
  2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project; whatever name you wish, and click OK.
  3. After clicking, the Window given below will appear. Choose an empty project template and check MVC option. 

The preceding step creates the simple empty ASP.NET MVC Application without Model, View, and Controller. The Solution Explorer of the created Web Application will look as shown below.



Step 2


Adding Web Service reference


There are many ways to consume Web Services but in this article, we will learn to consume the Web Service by using the Add Service reference method.


Note We are using Web Services, which are hosted in IIS. For more details, please watch my video by using the link given in the prerequisites section. The URL is given below, hosted by Service, which we are going to use in this application .




Right-click on the created ASP.NET MVC Application and click Add Service Reference, as shown below. 



Now, after clicking on the preceding Service reference option, it will show the Window given below.



Now, click on advanced button. It shows the Window given below, which allows us to configure how the entities and output should behave. 



After configuring the approriate Service reference settings, click Add Web Service reference. It will show the Window given below.



As shown in the preceding image, our Web Service found two web  service methods which are highlighted with a red rectangle. Now provide the web service reference name as you wish and click on ok , it will add the Web Service reference in our created ASP.NET MVC application, as shown below.



As you can see in the preceding highlighted square section, the Web Service reference gets added into our created ASP.NET MVC application. Now, we are done with adding the Web Service reference.


Step 3


Add Controller Class


Now, let us add ASP.NET MVC controller, as shown in the screenshot given below.  


After clicking


button, it will show in the Window. Specify the

Controller name

as Home with suffix


Now, let’s modify the default code of Home controller. After modifying the code of Homecontroller class, the code will look, as shown below.



  1. using System.Linq;  
  2. using System.Web.Mvc;  
  4. namespace ConsumingWebServiceInASPNETMVC.Controllers  
  5. {  
  6.     public class HomeController : Controller  
  7.     {  
  8.         // GET: Home  
  9.         public ActionResult Index()  
  10.         {        
  11.             return View();  
  12.         }  
  14.         [HttpGet]  
  15.         public JsonResult BookingStatus()  
  16.         {  
  17.             //Creating Web Service reference object  
  18.             HotepBookingPayReference.PaymentWebService objPayRef = new HotepBookingPayReference.PaymentWebService();  
  20.             //calling and storing web service output into the variable  
  21.             var BookingStatusInfo = objPayRef.RoomBookingStatus().ToList();  
  22.           //returning josn result  
  23.             return Json(BookingStatusInfo, JsonRequestBehavior.AllowGet);  
  25.         }  
  28.     }  

I hope, you have gone through the same steps and understood about how to use and call ASP.NET Web Service.


Step 4


Create Empty View


Now, right click on Views folder of the created Application and create View, which is named by Index, to display hotel booking details from hosted ASP.NET Web Services, as shown below.


Now, click Add button. It will create a View named index. Now, modify the code and write the jQuery function to bind the HTML table, using JSON data after modifying the default code. The code snippet of the Index View looks, as shown below. Index.cshtml

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4. “~/Scripts/jquery-1.10.2.min.js”>  
  5. “~/Scripts/jquery-1.10.2.intellisense.js”>  
  7. “text/javascript”>  
  9.     $(document).ready(function () {  
  11.         $.getJSON(“/Home/BookingStatus”function (data) {  
  14.             var tr;  
  15.             $.each(data, function (d,i) {  
  18.                 tr = $(
  19.                 tr.append(“ “ + i.RoomId + 


  20.                 tr.append(“ “ + i.RooType + 


  21.                 tr.append(“ “ + i.BookingStatus + 


  22.                 $(‘#tblBookingStatus’).append(tr);  
  26.             });  
  28.         });  
  32.     });  
  36. class=“form-horizontal”>  

    “tblBookingStatus” class=“table table-responsive” style=“width:400px”>  





  58.                     Room Id  
  61.                     Room Type  
  64.                     Booking Status  



  •     </div> 
  • The preceding View will display all hotel booking details. Now, we have done all the coding.

    Step 5


    Run the Application


    After running the Application, the hotel booking details from hosted ASP.NET Web Service will look, as shown below.

    I hope, from the above examples, you have learned how to consume ASP.NET Web Services in ASP.NET MVC Application.


    • Download the zip file of the published code to learn and start quickly.
    • This article is just the guideline on how to consume ASP.NET Web Service in ASP.NET MVC Application.
    • In this article, the optimization is not covered in depth; do it as per your skills.

    Summary I hope this article is useful for all the readers. If you have any suggestions, please mention them in the comments section.

    Read more articles on ASP.NET

    Salı, 07 Mart 2017 / Published in Uncategorized

    IntroductionWeb applications work on HTTP protocol and HTTP is a stateless protocol. Every HTTP request is treated as an independent request. The Server does not have knowledge about the variable values, which are being used in the previous request.


    Session is a feature in ASP.NET Core that enables us to save/store the user data. Session stores the data in the dictionary on the Server and SessionId is used as a key. The SessionId is stored on the client at cookie. The SessionId cookie is sent with every request. The SessionId cookie is per browser and it cannot be shared between the browsers. There is no timeout specified for SessionId cookie and they are deleted when the Browser session ends.At the Server end, session is retained for a limited time. The default session timeout at the Server is 20 minutes but it is configurable.Sessions are of two types, namely In-Proc or In-memory and Out-Proc or Distributed session. If our session is in-memory and our application is hosted on Web-Farm environment, we need to use sticky sessions to tie each session to a specific Server whereas an Out-Proc session does not require sticky sessions and they are the most preferred way to use sessions in our application.


    Configuring sessionMicrosoft.AspNetCore.Session package provides middleware to manage the sessions in ASP.NET Core. To use session in our Application, we need to add this package as a dependency in project.json file.



    1. {  
    2.   "version""1.0.0-*",  
    3.   "buildOptions": {  
    4.     "debugType""portable",  
    5.     "emitEntryPoint"true  
    6.   },  
    7.   "dependencies": {},  
    8.   "frameworks": {  
    9.     "netcoreapp1.0": {  
    10.       "dependencies": {  
    11.         "Microsoft.NETCore.App": {  
    12.           "type""platform",  
    13.           "version""1.0.1"  
    14.         },  
    15.         "Microsoft.AspNetCore.Mvc""1.0.1",  
    16.         "Microsoft.AspNetCore.Server.Kestrel""1.0.1",  
    17.         "Microsoft.AspNetCore.Routing""1.0.1",  
    18.         "Microsoft.AspNetCore.Session" : "1.0.1"  
    19.       },  
    20.       "imports""dnxcore50"  
    21.     }  
    22.   }  
    23. }  

    The next step is to configure session in Startup class. We need to call "AddSession" method in ConfigureServices method of startup class. The "AddSession" method has one overload method, which accepts various session options such as Idle Timeout, Cookie Name and Cookie Domain etc. If we do not pass the session options, the system will take the default options. Now, we need to call "UseSession" method in Configure method of startup class. This method enables the session for the Application.



    1. using System;  
    2. using Microsoft.AspNetCore.Builder;  
    3. using Microsoft.AspNetCore.Hosting;  
    4. using Microsoft.AspNetCore.Http;  
    5. using Microsoft.Extensions.DependencyInjection;  
    7. namespace WebApplication {  
    8.     public class Startup {  
    9.         public void Configure(IApplicationBuilder app)  
    10.         {  
    11.             app.UseSession();  
    12.             app.UseMvc();  
    13.             app.Run(context => {  
    14.                 return context.Response.WriteAsync("Hello Readers!");  
    15.             });  
    16.         }  
    18.         public void ConfigureServices(IServiceCollection services)  
    19.         {  
    20.             services.AddMvc();  
    21.             services.AddSession(options => {   
    22.                 options.IdleTimeout = TimeSpan.FromMinutes(30);   
    23.             });  
    24.         }       
    25.     }  
    26. }  

    It is important to call "UseSession" method before the "UseMvc" method in Configure method of startup class. If we call “UseMvc” method before “UseSession” method, the system will throw an exception.



    How to access the sessionWe can use session from HttpContext, once it is installed and configured. To use session in controller class, we need to reference "Microsoft.AspNet.Http" in controller. There are three methods that enables us to set the session value, which are Set, SetInt32 and SetString. The "Set" method accepts byte array as an argument. The SetInt32 and SetString method are the extension methods of Set and they internally cast byte array to int and string respectively. Same as there are three methods that  are used to retrieve the value from the session: Get, GetInt32 and GetString. The Get method returns byte of arrays.


    The main reason behind storing bytes array is to make sure that session values are serializable for the storage on remote Servers. Apart from int and string, we need to serialize to byte array to store it in session.


    ExampleIn the example given below, I have set my name into session in first request and retrieved the session value in another request.

    1. using Microsoft.AspNetCore.Http;  
    2. using Microsoft.AspNetCore.Mvc;  
    4. public class HomeController : Controller  
    5. {  
    7.     [Route("home/index")]  
    8.     public IActionResult Index()  
    9.     {  
    10."name","Jignesh Trivedi");  
    11.         return View();  
    12.     }  
    13.     [Route("home/GetSessionData")]  
    14.     public IActionResult GetSessionData()  
    15.     {  
    16. = HttpContext.Session.GetString("name");;  
    17.         return View();  
    18.     }  
    19. }  



    Custom Session Extension methodsAs discussed earlier, there are two extension methods to get the data from session and set the data to session are available, namely GetInt32 and GetString, SetInt32 and SetString. Similarly, we can add our custom extension methods to get and set the value in session.In the example given below, I have created an extension method to set double value to session and get double value from session.

    1. using System;  
    2. using Microsoft.AspNetCore.Http;  
    3. public static class SessionExtensions  
    4. {  
    5.     public static double? GetDouble(this ISession session, string key)  
    6.     {  
    7.         var data = session.Get(key);  
    8.         if (data == null)  
    9.         {  
    10.             return null;  
    11.         }  
    12.         return BitConverter.ToDouble(data, 0);  
    13.     }   
    15.     public static void SetDouble(this ISession session, string key, double value)  
    16.     {  
    17.         session.Set(key, BitConverter.GetBytes(value));  
    18.     }  
    19. }  

    Usage of the extension method

    1. using Microsoft.AspNetCore.Http;  
    2. using Microsoft.AspNetCore.Mvc;  
    3. public class HomeController : Controller  
    4. {  
    6.     [Route("home/index")]  
    7.     public IActionResult Index()  
    8.     {  
    9.         HttpContext.Session.SetString("name","Jignesh Trivedi");  
    10.         HttpContext.Session.SetDouble("Percentage",75.56);  
    11.         return View();  
    12.     }  
    13.     [Route("home/GetSessionData")]  
    14.     public IActionResult GetSessionData()  
    15.     {  
    16. = HttpContext.Session.GetString("name");  
    17.         ViewBag.Percent = HttpContext.Session.GetDouble("Percentage");  
    18.         return View();  
    19.     }  
    20. }  



    Store Complex Data in to SessionAs we are aware, session is able to store only byte of an array. Compared to the previous version, ASP.NET Core does not perform any operation such as serialization/ de-serialization on the values stored in session. Here, I am converting the complex object into JSON and store it as a string. Later, I am retrieving it as a string and de-serialize to original object.Thus, I have written the extension method for set and get complex object to session.

    1. using System;  
    2. using Microsoft.AspNetCore.Http;  
    3. using Newtonsoft.Json;  
    5. public static class SessionExtensions  
    6. {  
    7.     public static T GetComplexData<T>(this ISession session, string key)  
    8.     {  
    9.         var data = session.GetString(key);  
    10.         if (data == null)  
    11.         {  
    12.             return default(T);  
    13.         }  
    14.         return JsonConvert.DeserializeObject<T>(data);  
    15.     }   
    17.     public static void SetComplexData(this ISession session, string key, object value)  
    18.     {  
    19.         session.SetString(key, JsonConvert.SerializeObject(value));  
    20.     }  
    21. }  

    Usage of the extension methodIn the following example, I have created one public class and within controller action method, created the instance of the class, stored some data and sent it for storing in session. Similarly, I created one action method to retrieve the complex data from session.

    1. public class User   
    2. {  
    3.     public string Name { getset; }  
    4.     public double Percentage { getset; }  
    5. }  

    Action method

    1. [Route("home/SetComplexData")]  
    2. public IActionResult SetComplexData()  
    3. {  
    4.     User user = new User();  
    5.     user.Name = "Jignesh Trivedi";  
    6.     user.Percentage = 75.45;             
    8.     HttpContext.Session.SetComplexData("UserData", user);  
    9.     return View("index");  
    10. }  
    11. [Route("home/GetComplexData")]  
    12. public IActionResult GetComplexData()  
    13. {  
    14. = HttpContext.Session.GetComplexData<User>("UserData");  
    15.     return View();  
    16. }  

    SummaryThe main advantages of ASP.NET Core is that it supports modularity. It means that we need to add the module, as we wish to use it in our application. The usage of session is slightly different than the classic ASP.NET Application. This article helps us to understand how to install, configure and use session with ASP.NET Core.