Fluent Validation in an ASP.NET Core Web API

Fluent Validation allows you to separate validation rules from your model and helps you structure the rules so that they are nice and readable. The rules are also super easy to test.

Some existing code

Let’s say we have started to build a web api to add new customers:


Our NewCustomer model is:


We also have an action filter which will handle validation on the models and return a 400 if they are invalid:


Startup.ConfigureServices looks like this to wire everything up:

So, let’s say we want to make CustomerName a required field in the POST method on the newCustomer model. We could use a standard data annotation:

However, we’re not going to do this. Instead, we’re going to use Fluent Validation to keep our validation logic separate from the model and go on to add more complex rules …

Getting started with Fluent Validation

First we need to bring this library in via nuget. The packge that needs adding is FluentValidation.AspNetCore.
We can then wire this up in Startup.ConfigureServices by adding AddFluentValidation() to AddMVC():


Now let’s add a validation to ensure CustomerName is populated on the newCustomer model using the power of Fluent Validation:


As you can see, this rule is nice and readable. This class is also picked up automatically with the work we have already done in Startup.ConfigureServices.

To check this is working, let’s try to POST a customer without a surname to our API – we should get a 400 with a nice error message in the response body:

Adding some more simple rules

There’s quite a few built in rules in Fluent Validation, including a rule to validate an email address. So, let’s use this:


We can also add multiple rules on a field. Let’s add minimum and maximum length rules on CustomerName:


Again, this is nice and readable.

Conditional rules

So far the rules have been nice and simple. Let’s deal with more complex rules, starting with conditional rules. For example, a rule to ensure the first name is populated if the customer type is a person:


As well as implementing this rule, we’ve also made CustomerType a required field.
What about controlling the error message? At the moment we just get:
‘First Name’ should not be empty.
Let’s change the message to:
‘First Name’ must be filled in for customers of type ‘Person’.
All we need to do is chain a WithMessage() on the rule:

Custom rules

Lastly, we’ll look at a custom rule to ensure the company type is “Person” or “Company”. The rule will be called ValidCustomerType and invoked like below:


We define the rule like so:


We also need to define this validator in a static class (along with any other custom rules):

Unit tests

I introduced this post by saying how simple these rules are to test. The following tests are a few we could write against CreateCustomerValidator using Fluent Validation helpers ShouldHaveValidationErrorFor and ShouldNotHaveValidationErrorFor:

Conclusion

As you can see Fluent Validation is a great library for creating validation rules outside your model. I’d encourage you to check out the project on Github.

Connect with me:RSSGitHubTwitterLinkedIn

Creating a Multi-Tenant ASP.NET Core Web API with SQL Server RLS

In this post we’re going to leverage SQL Server Row Level Security (RLS), Entity Framework Core and ASP.NET Core to create a multi-tenant database with a multi-tenant web API …

First, let’s create a database containing a couple of tables – one to hold our tenants and one to hold some real data (products in this example):

We’ll add some test data in there as well. We’ll have 2 tenants – one with 3 products and the other one with 2 products:

Before we move on to RLS, let’s create a “super user” that will have access to data in all the tenants (this is useful for debugging). While we are at it, we’ll create a “normal user” that our web API will use to access data:

Now on to the RLS. First we need to create a predicate function that is going to apply a filter when the product table is accessed for the given tenant. The tenant for a given row is passed into the function. The tenant that the API is operatoring for is stored in SESSION_CONTEXT('TenantId') – we’ll come on to how this is set in the web API soon. We also need to make sure our super user has access to all the rows in the table

Now we can bind our predicate function to our product table. The FILTER predicate ensures we only read data for a given tenant and the BLOCK predicate ensures we only write data for a given tenant:

So, let’s give this a quick test, connecting as normaluser:


We should get following results back (3 rows for the first query and 2 for the 2nd query):

If you connect as superuser, SELECT * FROM dbo.Product, you should get all 5 rows.

Cool, we’re done with our database. Let’s move on to our web API …

Let’s create a new ASP.NET Core Web Application in Visual Studio, choosing the Web API project template.

First let’s create our model classes to hold our tenants and products …

Now, we’ll bring in EF core using nuget (I’m using the stable 1.1.2 packages). We’ll need Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer.

Time to create our EF core data context. Here’s a basic class that maps our tenants and products:

We’re not done with DataContext yet – we need to set SESSION_CONTEXT('TenantId') for every query that EF core does … we’ll come back to this after we’ve got the tenant from the API.

So, let’s create some middleware that will inspect the API key from the request to determine the tenant:


Please note the highlighted line in the above code where we place the tenant in a dictionary in the HttpContext. This is how we are going to get the tenant in DataContext.

Before we go back to DataContext, let’s go and do all our registrations in Startup:

Time now to go back to DataContext.
We can set the tenant in our constructor:

We can then set SESSION_CONTEXT(‘TenantId’) every time a connection is opened before any queries are run by EF core.

Ok, we’re done with DataContext now. Let’s create a simple API now to get some products:

Let’s check this is working in Postman with our 2 API keys. We should get 3 products for the 1st key and 2 products for the 2nd key:

Cool, we are good. Let’s quickly add an action method to get a product by its id:

Now let’s create the action method in our API to post new products:


… and let’s give it a try:

… it blows up!

We obviously have a problem because we are not submitting the tenant id in the product.

I lied when I said we were done with our database! Let’s add a default value for the tenant id that picks up SESSION_CONTEXT(‘TenantId’):

Now, when you post a product in Postman, we should be ok:

To finish off our controller we’ll quickly implement a PUT and DELETE:

Pretty straightforward and they both work. If you try to PUT and DELETE products that belong to a tenant that your API key is not for then you get a 404 – just as we want.

The great thing about this approach is that there is no reference to the tenant in our controller code – the multi-tenancy is taken care for us lower down in the stack which reduces our development costs and risk of leaking data.

Connect with me:RSSGitHubTwitterLinkedIn

HttpContext in ASP.NET Core

HttpContext is largely the same in asp.net core as it’s always been. However, one difference is that it is not automatically as available everywhere in your code base as it used to be …

If you are in a controller then you are okay – HttpContext is a property of ControllerBase:

If you are in middleware then you are okay – HttpContext is passed in as a parameter:

However, if you are in the domain layer, the you need to do some work …

First you need to register IHttpContextAccessor for dependency injection in the apps Startup class:

In your domain layer, you then need to bring in Microsoft.AspNetCore.Http via nuget and use dependency injection to get a reference to IHttpContextAccessor which in tern gives you a reference to HttpContext

Connect with me:RSSGitHubTwitterLinkedIn

Integrating Validation in Angular 2 and ASP.NET Core

I’m building an Angular 2 app with an ASP.NET core web API behind it and need to add some validation. Obviously, I need to validate on the server in the web API, but I also want to do some client validation to make sure the user experience is good …

Server Validation

Here’s my model, which you can see is using attributes to define some required field validation:

Here’s our controller below.

If the required fields aren’t filled in (detected from the attribute validation) a HTTP 400 status code is returned with the validation errors in the response body.

We also do some more complex validation, checking if the email address is already in use. Again we return a 400 and the validation error if the email address exists in our database.

So, let’s test our API in Postman.

Test that required fields are validated:

Test that a valid person is saved:

Test that a person with an email address already in the database is validated:

Wiring up our Angular 2 app

Now, that we have our web API in place, let’s build our page to submit a new person.

At this point we’re not going to implement any clientside validation – we’re just going to handle the validation coming from the server.

Here’s our component markup:

  • Lines 1-7 will show the validation errors from the server
  • Lines 8-10 will show confirmation that the person has been saved into the database ok
  • Line 12 defines our form, telling angular that the form object will be called personForm and submit handler will be a function called onSubmit
  • Lines 14-46 define our field inputs for the person
  • Lines 48-52 defines our submit button

Here’s our component code:

  • Line 14 defines a variable called errors which will be an array of validation errors
  • ngOnInit on line 19 creates our form object with no client side validation defined at the moment
  • onSubmit posts the person object to our web API. You can see we catch validation errors on lines 47-55, pushing them to the errors array

If you run the app and hit the Submit button without filling in the inputs, you get something like:

Client Validation

Now, let’s implement the client validation in the angular app.

First, we need to change ngOnInit to include the validation rules:

Then, we need to change our markup for the field inputs to output the validation errors. Here’s the markup for the title input:

  • Line 1 adds the has-error CSS class if we have touched and not filled in the input
  • Lines 13-16 displays the error message beneath the input if we have touched and not filled in the input

So, cool, if the user doesn’t fill in any of the inputs, validation errors will be shown before the submit button is pressed:

However, what if we enter a duplicate email address:

As you can see, the validation error from the server is shown which is good, but ideally we want to highlight the email input and display the error beneath it. So, we need to integrate our validation errors from the server into Angular’s validation.

The solution is in the highlighted lines below. We know the field name from the server’s validation error dictionary. So, if the field is on our form, we flag to angular that there is an error using the control’s setErrors function.

In our example, we don’t have any validation that is not bound to a single field (cross field validation), but if we did, the validation errors would be shown at the top of the page.

Now, if we try to input a duplicate email, our user experience is much nicer:

If you want to learn more about making Angular and ASP.NET core work well together, I’d recommend reading ASP.NET Core and Angular 2

Connect with me:RSSGitHubTwitterLinkedIn

Testing EF Core Repositories with xUnit and an In Memory Db

I came across the EF Core In Memory database recently. It obviously won’t have all the features of a relational database but it might be useful when unit testing simple repository methods.

Let’s take it for a spin …

Starting point

We have the following repository that we want to test. We’re just going to test the Add method in this post:

Here’s the EF data context and models behind our repository:

xUnit

So, let’s bring in xUnit by adding the following entries into project.json:

We also need to tell Visual Studio that xUnit is going to be our test runner by setting the following as a root property in project.json as well:

Now we can start adding xUnit tests. Let’s just add a couple of simple tests to double check xUnit is wired up properly. Let’s add the following class containing a test that should pass and a test that should fail:

If we open up Test Explorer you’ll see our tests and if you run them, 1 should pass and should 1 fail.

As a bonus, you can also run these tests from the command line by browsing to the app’s folder and running the following command:

Again, you should see 1 passing and 1 failing test.

In Memory Database

Before we test our repository, let’s bring in the In Memory database into our solution by adding the following dependency in project.json:

Repository Tests

So, let’s start testing our Add method in our repository by creating a class and a method to test the storyline when a person has no email address:

GetInMemoryPersonRepository is a method that all our tests will use to spin up a PersonRepository containing no data. Line 26 tells our data context to use the In Memory database. Lines 29 and 30 ensures we have a new database with no data in it.

The test is straight forward. Lines 6-12 creates a repository and a person with no email address. Line 14 calls the Add method in our repository passing in the person. Lines 16-19 carry our checks.

If you run the tests, all should be good.

Now, let’s add a couple more tests to test adding a person with single and multiple email addresses:

The tests are straightforward, following the same structure as the 1st test, using GetInMemoryPersonRepository to spin up a PersonRepository with an In Memory database behind it.

If you run the tests, all should be good.

The tests are also quick – on my machine the three tests took 7, 13 and 624 ms.

Connect with me:RSSGitHubTwitterLinkedIn

Getting Started With EF Core Migrations

Entity Framework (EF) migrations are a way to modify the database through different iterations of the software. Let’s have a play with these in EF Core in a web API project …

Models

Lets start with the following simple models to hold data about people:

Adding Entity Framework

Now let’s add EF to our solution in project.json (I’m still using .NET core 1.0):

DataContext

Let’s add the following data context:

Wiring EF up

To wire the app up to EF, first let’s add the following line to Startup.ConfigureServices:

We then need to add the following line in appsettings.json:

First migration

So, let’s have a go at our first migration …

Open a command prompt, browse to your solution directory and enter the following command:

After a second or so, our first migration will have been created in a Migrations folder in our solution:

Let’s have a look in the *_init.cs file. Cool, I can see an Up() method creating the 3 database tables and a Down() method droping the 3 tables. So, we have code that is going to create our schema which we can nicely source code control.

Let’s have a look at the PersonDataContextModelSnapshot.cs. As the name suggests, this looks like a copy of the schema – to faciliate the next migration generation.

But what will the generated migration SQL look like? Go back to the command prompt and enter:


The SQL will be output to the screen (you can output to a file by using the command dotnet ef migrations script -o {filename}).

The script creates a table called __EFMigrationsHistory which I didn’t create in my model. This will hold the list of migrations. You can see it adding our *_init migration at the bottom of the script.

I like that the primary keys have been correctly implemented as identities in the script. I like the foreign keys … I’m not liking the varchar(max) all over the place though!

Let’s fix the varchar(max) problem by adding the following code into PersonDataContext which specifies table names, field lengths and required fields in our schema:

So, let’s see what the script looks like now. First we need to remove our last migration by entering the following command:


You’ll notice the Migrations folder is now empty in our Visual Studio solution.

Now run the following command to generate the new migration and output the SQL script:

That’s much better!

Creating the database

So, let’s create the database by running the following command:


After a few seconds, the database will have been created. You should be able to see the database in Visual Studio in the SQL Server Object Explorer

Second migration

Now, let’s implement a model change. We’re going to add a Created property to our Person model:

Let’s create that migration:

If you open up *_Person_Created.cs you’ll see the migration to add our new column.

Before updating our database again, let’s check our SQL migration script. We need to specify the migration we want to start from which in my case in 20170125045706_init:

This looks good.

Updating the database

So, let’s update the database by running the following command:


After a few seconds, the column will have been added to the database:

Connect with me:RSSGitHubTwitterLinkedIn

Getting the right version of TypeScript in a Visual Studio ASP.NET Core Project

I’m building an ASP.NET Core Angular 2 app. I think I’m using the latest version of TypeScript (2.1 at the moment) but I’m not sure …

If I open a command prompt and type:

it gives me:

So, great, my app must be using the 2.1?

Let’s check this by writing some 2.1 code:

Visual Studio complains straight away, putting a red squiggly line under the ...‘s. If you hover over the complaints, you get a tooltip saying “property assignment expected“.

Lets try running the app. It runs perfectly fine with mergedPerson correctly outputted to the console.

What’s going on? The visual studio compiler must be using a different version of TypeScript.

For classic ASP.NET projects, TypeScriptToolsVersion in csproj used to define the TypeScript version but that is no longer the case in ASP.NET core. In ASP.NET Core, this appears to be defined in a file called Microsoft.TypeScript.targets at C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\TypeScript:


So, this makes sense – Visual Studio appears to be using v1.8 (line 4).

Unfortunately, simply changing the 1.8 to 2.1 didn’t work for me.
I looked in my C:\Program Files (x86)\Microsoft SDKs\TypeScript directory. I only had a folder for 1.8.

Visual studio was obviously missing something, so, I downloaded and installed the latest version of TypeScript for Visual Studio.

Voila! The red squiggly lines disappeared in Visual Studio, my app still ran fine and the version references in C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\TypeScript\Microsoft.TypeScript.targets has been upgraded to 2.1.

Connect with me:RSSGitHubTwitterLinkedIn

Enforcing HTTPS in ASP.NET Core

Enforcing ASP.NET Core web apps to use HTTPS is a little different to how you used to do it in previous versions of ASP.NET …

Setting HTTPS Up in Dev

Setting HTTPS up on our development version is simple. Just open the project properties, go to the Debug section, make sure you are running under IIS Express and tick Enable SSL.

Now, you should be able to run the app using the HTTPS URL.

The first time you navigate to the URL you’ll get a warning because the certificate is self-signed. You can however nagivate past this warning to the app’s home page:

Using middleware to enforce HTTPS

Our web app still doesn’t force users to use the HTTPS URL though. In my example, I can still browse to the web app via http://localhost:36313/.

We can force use of the HTTPS URL in ASP.NET Core’s middleware pipeline using the following code in startup.cs in the Configure method. Lines 17-28 is where we redirect if the URL is not HTTPS.

However, when we run the app we get the following error.:

This is because the HTTP and HTTPS ports are different and we haven’t taken that into consideration in our code.

Now, for development, the SSL port is stored in launchSettings.json (under the Properties folder in Visual Studio) under iisSettings > sslPort.

We can retreive this setting using the following code:

The redirect URL can then be built up as follows:

So, here’s our final pipeline code:

Connect with me:RSSGitHubTwitterLinkedIn

Taking Stripe Payments with Angular 2 and ASP.NET Core

Stripe is a service that allows you to very easily take payments online. In this post, I’ll go through how to take a payment via stripe using an Angular 2 frontend and an ASP.NET Core backend.

Sign up to Stripe

Firstly, we need to sign up for a stripe account. You can signup for a free test account here

After you have signed up, we need the Secret and Publishable keys. You can get these from Your account > Account settings > API Keys

Frontend Page

Let’s build the frontend first, using an Angular 2 component.

We are going to use stripe checkout which is super easy to implement and protects us from any PCI headaches (as long as our site runs on HTTPS).

First, we need to add a reference to the standard stripe checkout JavaScript in our server side ASP.NET Core view (line 3). This adds the global variable StripeCheckout which we’ll reference in our angular component. Note that we can not add this script into our angular component template because angular will remove it.

Now let’s add our angular payment component …

Here’s the simple markup (referencing bootstrap classes) which allows a user to buy 3 products, a T-shirt, some trainers or some jeans. Each button will invoke a function in our component code to take the payment via stripe. We show whether the payment has been successful or not in the last div in the markup, referencing a property called takePaymentResult.

Our component code is below …

Our 3 button handlers at are the bottom of the code and simply call into openCheckout() passing the product name, amount (in pence) and a callback to get invoked when we receive a token from stripe.

openCheckout() references the global variable StripeCheckout from checkout.js. Firstly we configure StripeCheckout, passing our publishable key and then we open the stripe payment form passing in our product and amount for the transaction.

After the user enters their credit card details and presses the Pay button, these details will be sent to stripe to initiate the payment. Stripe will then return a token and our callback (takePayment()) will be invoked.

takePayment() will call our ASP.NET Core API (/api/stripepayment) using angular’s http service. This is where the stripe payment will be processed – we’ll implement this in a minute.

The status from the /api/stripepayment API response is put in takePaymentResult which will be presented in the UI by angular.

Web API

OK, on to our web API that processes the stripe payment …

First, we need to bring in stripe.net via nuget – it makes processing the payment very simple.

Below is the full API controller and the API request model, StripePaymentRequest

First we tell stripe our secret key (line 7). We then setup the stripe charge object, setting the token, amount and description (to the product name). We also set our payment reference in the MetaData dictionary so that we tie the payment in our app to the payment in stripe.

The charge is then made and the result (which includes whether the payment has been successful) is passed back down in the response.

Test it!

You can test different scenarios using stripe’s test credit card numbers here.

Connect with me:RSSGitHubTwitterLinkedIn

Calling an ASP.NET Web API from jQuery

I’ve been playing with ASP.NET Core Web API recently … here’s a quick post on calling one of these APIs using jQuery Ajax …

Creating the API

The API is going to allow clients to:

  • get a list of people
  • get a single person
  • create a new person

Here’s the very simple person model:

For simplicity, I’m going to use a hardcoded list of people and not going to persist the people in a database. Here’s the API controller constructor and the hardcoded list:

The action method in PersonController to get the list of all the people is very simple:

The action method in PersonController to get a single person is below. The person id will be passed in from the URL path. We return the “Not Found” HTTP status code if the id isn’t in our hardcoded list and the JSON represenation of the found person if it does exists.

The action method in PersonController to create a person is below. The person object is passed in from the HTTP body that has been posted. If the body is missing we return a “Bad Request” HTTP status code. If we do have a person object from the HTTP body then the person id is generated, the person is added to the hardcoded list and we return a “Created” HTTP status code with the person in the response body containing the generated person id.

As well as dealing with returning the HTTP status code and the response body, the call to CreatedAtRoute(), also sets the Location HTTP header to the URL that the client could use to request the person just created. This is the reason for the Get action method having the GetPerson name parameter in the attribute and being referenced as the first parameter in CreatedAtRoute().

Creating the frontend page

Below is the HTML markup (referencing bootstrap CSS classes) that allows the user get a list of people:

Below is JavaScript for the getPeople button click handler. We use $.ajax() to call our person API. It is important to set contentType to application/json or our API won’t be reached. We put the names of the people returned in a pipe delimited list into the getPeopleResult textbox if the API call is successful.

Below is the HTML markup (referencing bootstrap CSS classes) that allows the user to get a single person:

Below is JavaScript for the getPerson button click handler. The code is very simular to the getPeople button click handler except it calls the API to get a single person and outputs the single person’s name in the getPersonResult textbox.

Below is the HTML markup that allows the user to create a person:

Below is JavaScript for the create button click handler. Again we use $.ajax() to call our person API but this time we POST to it. We create an object literal containing the name and email of the person and use JSON.stringify() so this can be passed into the data option in $.ajax(). We set whether the operation has been successful in the postResult textbox along with the generated person id. It is worth noting that the data in the success callback is the original data and not the data in the response. The response body can be obtained from jqXHR.responseText.

Connect with me:RSSGitHubTwitterLinkedIn