ASP .NET Core RTM Roundup

As of this post in August 2016, .NET core is in RTM I wanted to round up a bunch of things as of now and update my earlier post on ASP .NET Core but also I intend to use this post as a way of gathering content I think is useful, I've made sure to keep things here that are about .NET core RTM or RC2 where noted.

Important note, this blog post serves as a collection of some things I've found on .NET core RTM. It will change as I add new things.

Roadmap Blog post from MSDN

Getting started

First and foremost and just to start us off right, we have getting started. The new docs site for ASP is brillant

Create an MVC Net Core web app in Visual studio.

Getting started with Visual Studio

Want to use the command line? Well you can do that now.

Simple as

mkdir aspnetcoreapp
cd aspnetcoreapp
dotnet new

Get started from the command line

Building stuff

Scott Hanselman walks through creating a small Web API in .NET Core in Exploring a minimal WebAPI with ASP.NET Core another from Scott where he jumps into Nancy FX Exploring a minimal WebAPI with .NET Core and NancyFX

David Paquette covers using View Components in ASP.NET core LOADING VIEW COMPONENTS FROM A CLASS LIBRARY IN ASP.NET CORE MVC

For more on View Components David has us covered with Goodbye Child Actions, Hello View Components

Chris Myers takes us into building a Web API that runs in Docker, it's a really great step by step guide Stateful Microservice with .NET Core, Docker, and PostreSQL

Laurent Kempe goes wild with .NET core in Docker on Azure Build, ship and run ASP.NET Core on Microsoft Azure using Docker Cloud

Jerrie Pelser gets into Tag helpers and using them in a web app Accessing the Request object inside a Tag Helper in ASP.NET Core

Joonas Westlin gives us a look using Azure AD in .NET Core ASP.NET Core 1.0 Azure AD Authentication

Matthew Jones with some dependency injection in ASP .NET core Getting Started with Dependency Injection in ASP.NET Core

More Dependency injection this time from Shawn Wildermuth ASP.NET Core Dependency Injection

Ben Cull shows how you can store session variables in ASP.​NET Core, and also use a backing store such as Redis or SQL Server Cache instead of the default in-memory implementation. Using Sessions and HttpContext in ASP.NET Core and MVC Core

This post on the ComponentOne blog is another in an ongoing series on how to build your own Tag Helper. TagHelpers : Authoring Nested TagHelpers in ASP.NET Core MVC

Jon Hilton shows how to Compile your changes on the fly with .NET Core Watch

Radu Matei has an Introduction to ASP.NET Core MVC API

Marius Schulz shows us how to go about Simulating Latency in ASP.NET Core

Ben Cull using Global Routes for ASP.NET Core MVC

Jürgen Gutsch how you can configure the length of time that static content such as Javascript files, images and stylesheets are cached on the client side. Add HTTP headers to static files in ASP.​NET Core

As of this post in August 2016, .NET core is in RTM I wanted to round up a bunch of things as of now and update my earlier post on ASP .NET Core but also I intend to use this post as a way of gathering content I think is…

Read More

ASP Web API with Azure Table Storage

Using ASP Web API with Azure table storage

We've already covered the basics of creating an ASP Web API project and the basics for Azure Table Storage

ASP WEB API intro

Azure Table Storage

For the sample code for this check out our GitHub

Now we're going to get into using both of these. Creating a simple ASP Web API to create data into an Azure Table storage and to get that data back out. We'll do some testing of the API with Postman

As earlier we're using Visual Studio 2015.

Lets get going

Create a Web API project

Create Web API Project

Add Azure Storage from nuget.

We'll create a new controller building on our last post on Azure Table storage. We'll go for a "PlayerController"

Create API Controller

Select "Web API 2 Controller" from the Add scaffold option.

In the model create an entity for Table Storage "PlayerEntity". The player entity will look the same as we had in our last post.

Player Entity

Now back to our controller, we want to create two methods a POST method to create a player and a Get method to get players for a sport.

    public List<PlayerEntity> Get(string sport)
    {
        List<PlayerEntity> _records = new List<PlayerEntity>();

        //Create a storage account object.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);

        // Create the table client.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        // Retrieve a reference to the table.
        CloudTable table = tableClient.GetTableReference("player");

        // Create the table if it doesn't exist.
        table.CreateIfNotExists();

        // Get All Players for a sport
        TableQuery<PlayerEntity> query = new TableQuery<PlayerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, sport));
        
        foreach (PlayerEntity entity in table.ExecuteQuery(query))
        {
            _records.Add(entity);
        }

        return _records;
    }

This is the same as we used in our last post on Azure table storage.

We create a storage account with a connection string.

The table client is created and this we check for the table "Player" if it doesn't exist we create it.

Azure Table storage is a partitioned database. For this demo we create a partition based on Sport. So we can create players for "Soccer", "Rugby" and "Hurling" and so on. The get method will then only return the players for the sport we want.

For the Post there are a few ways to pass parameters we'll keep it simple for now. We'll pass the parameters into the POST method.

    // POST api/Player
    public string Post(string sSport, string sRow, string sFirstName, string sLastName, string sClub, string sPostition)
    {
        string sResponse = "";

        // Create our player

        // Create the entity with a partition key for sport and a row
        // Row should be unique within that partition
        PlayerEntity _record = new PlayerEntity(sSport, sRow);

        _record.Sport_VC = sSport;
        _record.First_Name_VC = sFirstName;
        _record.Last_Name_VC = sLastName;
        _record.Club_VC = sClub;
        _record.Position_VC = sPostition;

        //Create a storage account object.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);

        // Create the table client.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        // Retrieve a reference to the table.
        CloudTable table = tableClient.GetTableReference("player");

        // Create the TableOperation object that inserts the customer entity.
        TableOperation insertOperation = TableOperation.Insert(_record);

        try
        {
            // Execute the insert operation.
            table.Execute(insertOperation);

            sResponse = "OK";
        }
        catch (Exception ex)
        {
            sResponse = "Failed: " + ex.ToString();
        }
        return sResponse;
    }

With this Post method, we can take the parameters passed in and then create a player in our Table storage.

Testing with PostMan

We will use Postman to do the testing if you don't have it go get it and check out this post on using Postman

Our Get method is simple it takes a parameter of sport and then will return all the players in that sport.

In post man we create a GET Request to

http://*LOCALHOST*/api/Player?sport=soccer

This will return a list of all players in Soccer.

To test the POST method change the method in Postman to "POST"

http://*LOCALHOST*/api/Player?sSport=soccer&sRow=52&sFirstName=Chris&sLastName=Smalling&sClub=Man Utd&sPostition=CB

That's it, since we kept our POST simple we just need to pass the parameters and we can add the player to the Azure table.

Coming soon we'll start to work on our POST method and passing the parameters in different ways.

For the sample code for this check out our GitHub

Using ASP Web API with Azure table storage We've already covered the basics of creating an ASP Web API project and the basics for Azure Table Storage ASP WEB API intro Azure Table Storage For the sample code for this check out our GitHub Now we're going to get into…

Read More

ASP WebAPI

ASP Web API

ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. Using ASP.NET Web API you can create a HTTP RESTful services.

HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.

Get Started

In Visual Studio create a new project and select "ASP.NET Web application" Under Web templates. (I'm using Visual studio 2015)

Create ASP Web API

On the ASP.NET template screen for .NET 4.6 Select "Web API" this will scaffold everything you need. So go ahead create your first project.

Once Visual Studio has created the project you will have 3 controllers AccountController, HomeController, ValuesController

WEBAPI Default Solution

ValuesController has already been created with sample code for the API.

Run the project in debug mode and in your browser Click the "API" option

http://localhost:*****/help

Will show a list of the API methods available.

With the values Controller we can see the break down of all the API Methods

http://localhost:*****/Help/Api/GET-api-Values

Will show you the break down of the method for Get, the parameters required and response.

Summary

This post covered the very basics of getting started with Web API in .net. We'll bring more posts that build on this post over the next few weeks.

ASP Web API ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. Using ASP.NET Web API you can create a HTTP RESTful services. HTTP is not just for serving up web pages. It is also a powerful platform for building APIs…

Read More

ASP MVC HTTPS and 301 Redirect

Last time around I explained how to get Lets encrypt up and running on Windows Azure to catch up click here

Now I have it running I need to get my sites to use HTTPS all the time and also use 301 Redirect for SEO goodness

All below works as of today on Visual studio 2015 and ASP 4.6 working site https://cloudstatus.eu

Force HTTPS

First step was to always require HTTPS. This in MVC 4 + is straight forward enough, in the controller. Simply add the [RequireHttps] to the top of each controller you want to force the SSL in.

[RequireHttps]
public class HomeController : Controller

Every time you open the controller it will send you to the HTTPS version of the page

IISExpress does have an issure here but it's easy to sort. You need to tell IIS Express it's ok to use SSL.

With the web project selected hit F4 to bring up the "Project Properties pane"

You should see an option "SSL Enabled" select True and then when you run the website it will open on the port set.

This now means that all requests to the site will be using the https. If a visitor uses http:// then it will be sent to the [RequireHttps] this will then send it with a redirect.

301 or 302 Redirect

RequireHttps sends a 302 redirect you can test your redirect here

302 Redirect is fine I think in most cases but it's a temporary redirect and Google isn't kind to that.

For SEO we need a 301 redirect but we can do that.

To sort this we need to create a custom RequireHttps attribute.

public class CustomRequireHttpsFilter : RequireHttpsAttribute
{
    protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
    {
        // If the request does not have a GET or HEAD verb then we throw it away.
        if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)
            && !String.Equals(filterContext.HttpContext.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
        {
            base.HandleNonHttpsRequest(filterContext);
        }

        // Update the URL to use https instead of http
        string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;

        // If it's localhost we are using IIS Express which has two different ports.
        // update the url with the IIS Express port for redirect on local machine.
        if (string.Equals(filterContext.HttpContext.Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase))
        {
            url = "https://" + filterContext.HttpContext.Request.Url.Host + ":44363" + filterContext.HttpContext.Request.RawUrl;
        }

        // Build the httpContext Response
        // Setting a status of 301 and then telling the browser what the correct route is.
        filterContext.HttpContext.Response.StatusCode = 301;
        filterContext.HttpContext.Response.AppendHeader("Location", url);
        filterContext.HttpContext.Response.End();
    }
}

Then we make a change to our filterConfig to call our CustomerRequirehttps

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CustomRequireHttpsFilter());         
    }
}

And that's it, all HTTP:// calls are sent into the custom Require and will return a 301 with the new URL.

Last time around I explained how to get Lets encrypt up and running on Windows Azure to catch up click here Now I have it running I need to get my sites to use HTTPS all the time and also use 301 Redirect for SEO goodness All below works as…

Read More