How To Create ASP.NET Core Web API in Visual Studio 2015

How To Create ASP.NET Core Web API in Visual Studio 2015 | Best and cheap ASP.NET Core 1.0 hosting. This tutorial lets us create very basic ASP.NET Core Web API using Visual Studio 2015. We will be creating Contacts API which lets do popular CRUD operations.

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices.

ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. Update 12/10 – Updated to ASP.NET Core 1.0 with EF Core

Step 1 : Contacts API Overview

The Contacts API is very simple, basic Web API which does CRUD operations. I have focused on writing web API rather than integrating it with databases.  This table summaries Contacts API which we’ll create


Step 2: Create ASP.NET Core Web API project

Install ASP.NET Core 1.0

Open Visual Studio 2015 Update 3, create “New Project” with name “ContactsApi

From ASP.NET Core templates select “Web API” as shown in image (I haven’t selected any Authentication, we will add them later)


Program.cs is newly added file, it’s entry point when application run, that’s right public static void main(). ASP.NET Core apps are considered as console apps.

Step 3: Packages included for ASP.NET Core Web API

The packages included are “MVC”, “EnvironmentalVariables”, “JSON”, “Logging”. (This is generated by default, do not copy this)

Step 4: Creating Contacts model

Contacts class is centre of this Web API project. Its POCO class containing some properties which are self explanatory.

Right click “ContactsApi” solution, create folder “Models“; under this “Models” folder create C# class “Contacts.cs” and copy this code

Step 5: Create and Register repository class for Contacts

The use of repository classes is really optional, but I have added it so that we can connect to any databases later.

Create “Repository” folder under “ContactsApi” solution, we will add one C# interface file and C# class file implementing this interface.

Create “IContactsRepository.cs” interface file in “Repository” folder and copy below code

Create “ContactsRepository.cs” class file, implement “IContactsRepository” and copy below code

ASP.NET MVC 6 provides out of box support for Dependency Injection, we will include that in our “ConfigureServices” method of Startup.cs.  We will see entire code in Step 7

Step 6: Add Contacts API Controller

Its time to add the controller API which acts as Web API. Create “Controllers” folder under “ContactsApi” project solution and add C# class file “ContactsController.cs“; copy below code

Some quick notes of this ContactsController

  1. [Route(“api/[controller]”)] – this used attribute based routing to access the ASP.NET Core Web API.
  2. ContactsRepo is instantiated using dependency injection which we configure in services.cs.
  3. GetAll() is simple HttpGet method which gets all contacts
  4. GetById fetches contact based on mobile phone. Its given HttpGet with Name attribute so that we can use that in Create method to be used for location header.
  5. Create method after inserting contact, returns 201 response and provides location header.

Note: HTTP Status codes are now written as BadReqest(), NotFound()Unauthorized() etc

Step 7: Enable CamelCasePropertyNamesContractResolver

Any Web Api (REST based) should return JSON response in form of Camel Case so that we can sure consume the API in any client. We need to enable CamelCasePropertyNamesContractResolver in Configure Services.

Here is the Startup.cs file which has all code needed for running this Contacts ASP.NET Core Web API.

How To Generating SEO (and user) friendly URLs in ASP.NET MVC

How To Generating SEO (and user) friendly URLs in ASP.NET MVC | Best and cheap ASP.NET MVC Hosting. In today’s blog post I would like to demonstrate how to generate “friendly” URLs in your ASP.NET applications. Friendly not just in the sense that someone can look at it and figure out what the URL is pointing to, but more importantly friendly for search engines.

Right now you may probably ask what difference it makes to search engines like Google what the URL of a page is? Surely a computer does not care? Well you would be sort of right, but the thing is that having keywords you are trying to rank for in the URL of a page, does indeed make a difference.

There are many things which play a role in how Google determines the ranking of a web page, and no one can say for certain exactly how big a part each of those factors play. What most people agree on however is that having the keywords you want a page to rank for in the URL of the page does indeed help with the ranking of the page.

In this blog post I am going to show you how to generate URLs in your application which is more SEO – and user – friendly.

Generate URLs

In my sample application I have created a fictitious product database which displays a listing of products, and allows a user to click on a specific product to navigate to the details page for that product.

My product class is fairly simple:

On the product listing page I simply display a list of products:


And when the user clicks on a specific product they are navigated to a product details page:


Take a look at the URL which we are generating:


It is just a normal URL as you get in most ASP.NET MVC application which passes along the ID of particular database row to the controller action.

We want to have something which is more user friendly. Something which at least also contains the name of our product. To generate a friendly URL I have created a new method on my Product class which generates a proper “slug” (or URL) for the product details page:

And I have also updated my listing page to use the slug as the route parameter instead of the Id as it did before:

Now when I navigate to the product detail page I can see that we have a proper “friendly” URL which contains the name of the product:


Parameter binding

But also notice that we have a new error. ASP.NET MVC is complaining that it was expecting an id route parameter, but could not find it. This is because the Details action on my controller is expecting an integer value for the id parameter:

But instead of an integer, the {id} part of our route now contains a string. The MVC framework is trying to convert the string to an integer, but cannot do it and therefore it is passing a null value along, and then complains that the id parameter cannot contain a null value.

To fix this error we need to modify the RouteData for the route to fix up the value of the id route parameter.

I have created a new class called SeoFriendlyRoute that inherits from Route and have overridden the GetRouteData method to clean up the id parameter. In my implementation I call the base GetRouteData method and check if the route data is not null, in which case it means that I have a match for my route.

In this case I simple check whether the id parameter is present and if it is I use a regular expression to extract the first part of the URL that contains the actual numerical ID, and I assign that numerical value to the id route value:

And the last bit is to add a new route for the path /products/details/{id} to use my new SeoFriendlyRoute route class:

And now when I refresh the page, the parameters are bound correctly as only the numeric part of the product URL that contains the actual product ID is passed along as the id parameter:


How To Migrate Joomla to New Server

How To Migrate Joomla to New Server | Best and cheap Joomla hosting. In this post we will show you tips to migrate joomla to new server. A Joomla website has to main components – files & folders and database. The files and folders contain all the scripts and coding stuff that works at the back-end and is required to control the outlook of a website. While the database contains all the records of a website including content, pages, and images. The migration of a Joomla website to a new server isn’t really a hectic process, however proper handling and step-following can make it a piece of cake.

Back up all the Files

First of all, login to your website through dashboard or control panel and download all the relevant files to your hard disk. You must be thinking of what program to use for this step; using FTP, FileZilla or Smart FTP would be fine. Make a proper directory such as “public_html” which is the default directory present in a server.

Database Backup

You got to have some tools and components installed on your website to make this step easy. You could use phpMyAdmin or the tools including LazyBackup or JoomlaPack. These two tools allow you to set up and download the record for relocation and also allow backups automatically. You can get backups to your email account if you use LazyBackup tool.

Export your Website

Once you have all the record with you, the next thing you have to do is to upload all the files to the new Joomla hosting by FTP in to that very server. It’s just the opposite step of the previous one so this doesn’t really take long.

Database Migration

To make this tricky step a little easier, go for the databse tool called phpMyAdmin, which would let you create a separate database and load all the previously saved record on it. The alternative way is to run MySQL commands but would take much more time than phpMyAdmin.

Updating the Configuration

Flawless configuration is a must. Make one mistake and you would be making this migration a headache for yourself. The .php files have to be configured in your website and uploaded again on the server. Each and everything including the username, password, database name, and relevant information, would be uploaded on the server. Once it’s done, you can enjoy seeing the website running on this new server.
Now change the log directories and temporary files and folders so that they can match up with the new server system. The variables that would have to be changed and updated are:


Test the Installation

You must be done by now, but watch out for anything that is left. Make sure the website is running properly and is allowing you to access the files or content properly, and most importantly do not forget to ensure the proper functioning of the control panel. If you are uncomfortable with it or are facing some issues, let it be fixed by some professional because a mistake done at the backend of website in the programming side can be disastrous if you are not familiar with the coding or scripting.

Tips for Building an API in ASP.NET Core

Tips for Building an API in ASP.NET Core | Best and cheap ASP.NET Core 1.0 hosting. These days users expect a fluid, app-like experience on the internet. Thus, the new web is being built with APIs and single-page frontends. This means it’s more important that ever to build APIs that are easy to use, reliable, and scalable. ASP.NET Core makes it easy to build great APIs, but there are a few tips we’ve picked up that can help make your APIs even stronger and more scalable.

1. Set the Default Route for ASP.NET Core MVC

A lot of programmers who start using ASP.NET Core just use the default app.UseMvc(); line in the Configure method of Startup.cs. There are options that you can pass to the UseMvc function, like setting the default routes, which is one of the most overlooked:

This will set the root route of your API to: to call the DefaultController’s Get method.

What this does for you (aside from the obvious) is it sets the tone for a decent RESTful API. It also makes changes to URL strategy easier, including versioning the API in the URL easy to do if you set the URL strategy in one place.

2. Return IActionResult from .NET Core Controller Methods

Returning IActionResult from your controller methods affords the ability to take advantage of some of the helper methods and classes to ease returning proper HTTP results. The Ok method on the ControllerBase class will return an OkObjectResult that implements IActionResult and returns a 200 OK HTTP message to the caller. The NotFound method returns an object that sends a 404 NOT FOUND HTTP message.

There are quite a few others, but another extremely helpful one is the CreatedAtAction class that returns not only a 201 CREATED HTTP result but adds a header Location with the URL to access the newly created resource.

3. Use the .NET Async Pattern

Network calls by their very nature are asynchronous. It makes the most sense to create async controller methods that extend that asynchronicity when the controllers need to make database and external API calls.

The fact is, asynchronous support in .NET Core and the supporting libraries is very good these days. Using and creating asynchronous code is easy using async/await and libraries that support the Task pattern. The benefit is more simultaneous requests handled with the same hardware requirements.

Asynchronous code just performs better, and since it is so easy to create, why not do it?

4. Use .NET Attributes

Using attributes to decorate routes helps you to take advantage of some of the power of MVC. This may seem counterintuitive since I just told you to use the default routes. Decorating your methods and controller classes with just enough decoration for that class or method can help you take advantage of things like the CreatedAtAction.

You can also use attributes to help the JSON serializer do its job. You can use the NullValueHandling attribute to tell the serializer that when the value of a property is null, not to even serialize the property. You can change the property name that gets serialized so that you can stick with an internal coding standard and still return standard JSON names (like changing ‘MaxTitleLength’ to ‘maxLength’ when serialized). You can even set the order that properties are serialized so that more important properties are serialized first in the JSON documents.

5. Use Async Result Filters

Using Async Result Filters, you can shape the data in the last moments before it goes back to the caller. Usually, you’d add the properties you want (the way you want them) via an anonymous object. There are two problems with that approach, the first is that you need to do a lot of copying of properties and it violates the single responsibility principle. You could use AutoMapper to combat this property copying, but it doesn’t solve the second problem, which is adding new properties (like hypermedia).

Solution: An Async Result Filter will solve both problems and give you a cleaner, more maintainable code base.

BONUS: Try This Workaround to Improve Serialization of Self-Referencing Object Graphs

One of the problems with traditional .NET Web API serialization, is that it doesn’t handle self-referencing object graphs very well. The fact is, in good object-oriented objects there may actually be some reference loops, so it’s important to handle them gracefully.

In your ConfigureServices method of Startup.cs, change your MVC line from:

to :

In .NET 4.x a reference loop would cause an error. Once the serializer realized that serializing the object graph would cause a reference loop, it would fail and just send a 500 error. However, in .NET Core without the above JSON options added, the serializer serializes the object until it hits a reference loop and simply sends what has been serialized so far, ignoring the rest of the object, even if it could serialize the rest of the object graph easily.

What this line adds is, it tells the JSON serializer to ignore reference loops and continue serializing the rest of the graph. So far, this is just a workaround for the issue. It’s not perfect, but it’s better than just a failure.

The best way to handle this problem is to simply not have the problem. Normally, we would put these objects into DTOs that are not self-referencing and remove the problem altogether.

How to Create Dynamic DropDownLists in ASP.NET

How to Create Dynamic DropDownLists in ASP.NET | Best and cheap ASP.NET hosting. In this post I will tell you how to create Dynamic DropDownLists in ASP.NET


  • Create dropdownlist dynamically with autopostback property true
  • Keep dropdownlist during postback
  • Maintain selected value during postback.

Here is the sample for this :

To Create Dynamic Dropdownlist:

To retrieve value on button click:

Right Now, No output because dynamic controls are lost in postback then what to do.
So we need to save dynamic controls value and generate dynamic controls again.we need to maintain viewstate.

How To Authentication in ASP.​NET Core for your Web API and Angular2

How To Authentication in ASP.​NET Core for your Web API and Angular2 | Best and cheap ASP.NET Core 1.0 hosting. In this post we will talking about Authentication in ASP.NET for web API and Angular. Authentication in a single page application is a bit more special, if you just know the traditional ASP.NET way. To imagine that the app is a completely independent app like a mobile app helps. Token based authentication is the best solution for this kind of apps. In this post I’m going to try to describe a high level overview and to show a simple solution.

There are many ways to protect your application out there. The simplest one is using an Azure Active Directory. You could also setup a separate authentication server, using IdentityServer4, to manage the users, roles and to provide a token based authentication.

And that’s the key word: A Token Based Authentication is the solution for that case.

With the token bases authentication, the client (the web client, the mobile app, and so on) gets a string based encrypted token after a successful log-in. The token also contains some user info and an info about how long the token will be valid. This token needs to be stored on the client side and needs to be submitted to the server every time you request a resource. Usually you use a HTTP header to submit that token. If the token is not longer valid you need to perform a new log-in.

In one of our smaller projects, didn’t set-up a different authentication server and we didn’t use Azure AD, because we needed a fast and cheap solution. Cheap from the customers perspective.

The Angular2 part

On the client side we used angular2-jwt, which is a Angular2 module that handles authentication tokens. It checks the validity, reads meta information out of it and so on. It also provides a wrapper around the Angular2 HTTP service. With this wrapper you are able to automatically pass that token via a HTTP header back to the server on every single request.

The work flow is like this.

  1. If the token is not valid or doesn’t exist on the client, the user gets redirected to the log-in route
  2. The user enters his credentials and presses the log-in button
  3. The date gets posted to the server where a special middle-ware handles that request
    1. The user gets authenticated on the server side
    2. The token, including a validation date and some meta date, gets created
    3. The token gets returned back to the client
  4. the client stores the token in the local storage, cookie or whatever, to use it on every new request.

The angular2-jwt does the most magic on the client for us. We just need to use it, to check the availability and the validity, every time we want to do a request to the server or every time we change the view.

This is a small example about how the HTTP wrapper is used in Angular2:

The ASP.NET part

On the server side we also use a, separate open source project, called SimpleTokenProvider. This is really a pretty simple solution to authenticate the users, using his credentials and to create and provide the token. I would not recommend to use this way in a huge and critical solution, in that case you should choose the IdentiyServer or any other authentication like Azure AD to be more secure. The sources of that project need to be copied into your project and you possibly need to change some lines e. g. to authenticate the users against your database, or whatever you use to store the user data. This project provides a middle-ware, which is listening on a defined path, like /api/tokenauth/. This URL is called with a POST request by the log-in view of the client application.

The authentication for the web API, is just using the token, sent with the current request. This is simply done with the built-in IdentiyMiddleware. That means, if ASP.NET MVC gets a request to a Controller or an Action with an AuthorizeAttribute, it checks the request for incoming Tokens. If the Token is valid, the user is authenticated. If the user is also in the right role, he gets authorized.

We put the users role information as additional claims into the Token, so this information can be extracted out of that token and can be used in the application.

To find the users and to identify the user, we use the given UserManager and SignInManager. These managers are bound to the IdentityDataContext. This classes are already available, when you create a new project with Identiy in Visual Studio.

This way we can authenticate a user on the server side:

And this claims will be used to create the Jwt-Token in the TokenAuthentication middle-ware:

This code will not work, if you copy and past it in your application, but shows you what needs to be done to create a token and how the token is created and sent to the client.

Claim Based Security on ASP.NET Core 1.0

Claim Based Security on ASP.NET Core 1.0 | Best and cheap ASP.NET Core 1.0 hosting. Even though the ASP.NET Web platform and ASP.NET project scaffold have undergone some significant changes, ASP.NET MVC Views and Controllers have faced rather minor transformation in comparison with the shift in skeleton of the Application with the new platform. So here’s a brief outline of the latest news in ASP.NET development.

In this article, I’m going to describe the main concepts of building claim-based security on top of a brand-new platform: ASP.NET Core (with .NET Core). At the same time, I will create an application with similar functionality (as was done in my previous article), highlighting the differences.

Let’s get down to work. Create a “Hello World” ASP.NET Core Web application using the .NET Core framework


Figure 1: Creating a new ASP.NET Core Web application

Just like in the previous version of ASP.NET MVC, the main job is done. The default Visual Studio .NET Web Project template has already added all the namespaces and assemblies required for our test project. The only thing left is to implement simple functionality to add a new Claim during the user registration/creational process and then apply the authorization restriction to the user with the Claim specified.

Let’s quickly review the most important pieces of functionality responsible for security work this time:

Startup.cs is a class for the entire application bootstrap, including security:

Models\ApplicationUser.cs contains an ApplicationUser class that derives from Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUser:

Until now, it’s been empty, so this is where we should add our claims. Let’s start applying code changes to demonstrate Claim-based security in real life:

1. Enable Entity Framework Migrations

Enable Entity Framework Migrations if there are any iterative changes to Claims planned. Because ASP.NET Identity uses Code First, auto-migration would be useful to perform database schema updates

2. Add Relevant Properties

Add all relevant properties to the ApplicationUser class (in file Models\ApplicationUser.cs) to store the Claims. Let’s take “BirthDate” and add this property to ApplicationUser. Don’t forget to add the using System clause before class definition.

3. Add EF Migration

Add EF migration to the update database with the new field. In the Package Manager Console, perform the following steps:

  1. Add-Migration “Age” <press Enter> to create an upgrade script for our modification.
  2. Update-Database <press Enter> to run a database schema update.

Now, we need to implement the filling out of the Birthday value. To make it more obvious, add a Birthday parameter to the User Registration form in the Models\AccountViewModels\RegisterViewModel.cs RegisterViewModel class:

4. Update the Views\Account\Register.cshtml File

Update the Views\Account\Register.cshtml file with the new field:

5. Update the Controllers\AccountController.cs Register Method

Update the Controllers\AccountController.cs Register method to pass Birthday:

6. Add the Claims

Now, we need to add the Claims. To be more precise, we need a mechanism to add the Claims in ASP.NET Core because Microsoft.AspNetCore.Identity.SignInManager<TUser>, by default, includes only username and user identifier claims. SignInManager<TUser> uses IUserClaimsPrincipalFactory<TUser> to generate ClaimsPrincipal from TUser (in our case, from ApplicationUser).

We need to create our own implementation of IUserClaimsPrincipalFactory<TUser> to add custom claims. To not generate the boilerplate code, simply derive it from the default UserClaimsPrincipalFactory<TUser> which is already implementing IUserClaimsPrincipalFactory<TUser>.

7. Register CustomClaimsPrincipalFactory

We need to register our CustomClaimsPrincipalFactory in Startup.cs after the Identity setup has been added:

8. Verify the Claim

We have implemented the Claims setup. The only thing left is to verify the Claim. It is a common practice to write custom Authorize filters to verify the availability and particular value of the Claim pair, and then put that filter on the controllers’ actions.

Claim BirthDay requires more checks, so I will implement verification of the Claim just for demonstration purposes in the Controllers\HomeController.cs About method:

Any Claim may be extracted easily from the HttpContext.User at any point of the project.

Traditionally, let’s try to verify if the code works.

Reviewing all the Claims (in debug window):


Figure 4: Viewing the Claims in the debug window


That was a step-by-step guideline to set up Claim-based security in ASP.NET Core with the help of ASP.NET Core Identity.

Compared to the previous-generation ASP.NET MVC, at first glance implementation of the Claim-based security looks more complicated in ASP.NET Core. Previously, it was possible to add the Claims directly in the ApplicationUser implementation via overriding the GenerateUserIdentityAsync() method. In ASP.NET Core, we need to implement IUserClaimsPrincipalFactory<TUser> that is internally used by SignInManager<TUser>. On the other hand, we’ve got more structured classes and interfaces implementation in ASP.NET Core, as logically SignInManager should indeed control sign-in processes (including claims) and ApplicationUser should be just an IdentityUser.

One more useful thing that was introduced in ASP.NET Core is Claim-Based Authorization on top of Policies. It simplifies the verification of Claims on Controllers and Methods, thereby providing an ability to group the Claims.

Configuration ASP.NET Core 1.0 Project

Configuration ASP.NET Core 1.0 Project | Best and cheap ASP.NET Core 1.0 hosting. According to tutorialspoint website about the configuration related to ASP.NET Core project. In Solution Explorer, you will see the Startup.cs file. If you have worked with previous versions of ASP.NET Core, you will probably expect to see a global.asax file, which was one place where you could write codes to execute during startup of a web application.

  • You would also expect to see a web.config file containing all the configuration parameters your application needed to execute.
  • In ASP.NET Core those files are all gone, and instead of configuration and startup code are loaded from Startup.cs.
  • There is a Startup class inside the file and in this class you can configure your application and even configure your configuration sources.

Here is the default implementation in the Startup.cs file.

In the Startup class, there are two methods where most of our work will take place. The Configure method of the class is where you build your HTTP processing pipeline.

  • This defines how your application responds to requests. Currently this application can only say Hello World! and if we want the application to behave differently, we will need to change the pipeline around by adding additional code in this Configure method.
  • For example, if we want to serve the static files such as an index.html file, we will need to add some code to the Configure method.
  • You can also have an error page or route requests to an ASP.NET MVC controller; both of these scenarios will also require to do some work in this Configure method.
  • In the Startup class, you will also see the ConfigureServices() method. This helps you configure components for your application.

Right now, we have a hard-coded string for every response — the Hello World! string. Instead of hard-coding the string, we want to load this string from some component that knows the text that we want to display.

  • This other component might load that text from a database or a web service or a JSON file, it doesn’t matter where exactly it is.
  • We will just set up a scenario so that we do not have this hard-coded string.

In the Solution Explorer, right-click on your project node and select Add → New Item


In the left pane, select Installed → Code and then in the middle pane, select the JSON File. Call this file AppSettings.json and click on the Add button as in the above screenshot.


We can also have our program read the text from the file instead of having the Hello World! String in Startup.cs. Let us add the following code in AppSettings.json file.

Now we need to access this message from the Startup.cs file. Here is the implementation of the Startup.cs file which will read the above message from the JSON file.

Let us now run the application. Once you run the application, it will produce the following output.


I hope this article helpful for you. Happy coding :)

Securing your ASP.NET MVC Application

Securing your ASP.NET MVC Application | Best and cheap ASP.NET MVC hosting. Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one’s web application.

By decorating the HomeController using the Authorize attribute (notice I didn’t specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there’s security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

Lastly, add the following to the project’s web.config file:


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 | 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.