Throttling actions in .Net Core 2.1 using AttributeFilter

I have previously written about Throttling in the pre-core times, and this is sort of the update to that post – with a bit of fixes and tweaks.

Lets get to it;

A few changes:

In my last post I did things a bit differently, for instance; I used to throw a custom exception type and handle that as a response, I have learned that this is an anti-pattern and is strongly discouraged (at least by David Fowler).
Anyway now we return a class, which is basically just my old ApiException type, just without the inherited bits of Exception. – this is both cheaper and cleaner.
Also since we are using .NET Core, we are using IMemoryCache instead of HttpRuntime.Cache – which is also nice.

services.AddMemoryCache();

On to the attribute:

There isn’t a lot to it to be honest.

  1. Check for existence of cache entry
  2. If none, create one and set allowExecute = true
  3. If allowExecute != true, return throttle response and short-circuit the pipeline.

Do note that this throttle uses IP as it’s target, but could easily be username or similar.

Usage:

[IPThrottling("GetItems", 300)]
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
    return new string[] { "value1", "value2" };
}

The above throttles for 300 seconds for the GetItems key, so you can group together functionality as well, if you really need to.

Ill talk about the custom response in a different blogpost

async await “explained” by examples

What does async and await really do?

Using the await keyword is basically just waiting for whatever function that comes after that keyword to create a thread, do work and return to the calling thread once it is done.
Everything that comes after is a “continuation”
The following 2 functions do pretty much the same thing

The above should also indicate something else, namely continuation.
In the first method everything after the “Task” calls would probably run before the tasks would finish.
In the latter, everything after the await call IS the continuation.
So doing something like the following;


Would result in the function taking around 6 seconds to do its “work”, since everything is a continuation of the former.
– this is probably not what you would want.
Instead you can do something like this;

Which would take around 2 seconds.

Exceptions:

Using async and await there is something to note in regards to exceptions:
I found this in an MSDN article and I think it explains it pretty well.

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. Exceptions thrown from async void methods can’t be caught naturally.

 https://msdn.microsoft.com/en-us/magazine/jj991977.aspx


The following code should explain:

So never ever use async void – it will take days to figure out what is actually going on.
If you have any questions please comment below and I will try to update the article with an answer 🙂

Easy, simple HttpRuntime.Cache

A simple to use caching function that both gets and/or sets the key depending on results.

This is a post for my future self. – Hi future self! (wave).
The following is an easy to use caching function.

The function gets or updates based on results.
The wrapper helps create different cacheExpirations based on needs.
Usage:

The ServiceActionResult Pattern. Part Two

Continuing from my previous post The ServiceActionResult Pattern
This could also be implemented in a Generic Repository Pattern. If you have read, any post about a using a generic repository, it usually looks something like this:

The interesting part is the Update/Delete/Insert methods.
Yes… you could return a boolean saying whether or not the transaction was successful.
But we could also use the ServiceActionResult “Pattern”, to make it look something like this;

Which gives us that nice granular return state AND the actual entity in question (which is nice for RESTful services)

The ServiceActionResult pattern

This is not a GOF pattern or anything, but it’s very nice and brings alot to the table.
Basically what I do is this;
Whenever I have some sort of Service/Repository or something similar. Basically any façade where I delegate to CRUD or do CRUD, I return a ServiceActionResult.
The ServiceActionResult class looks like the following:

It’s just a basic generic class that holds a class (T) and an Enum.
The Enum could look something like this, but could be anything you’d like.

It’s kinda like REST.
Return the entity and an HTTP Status code, but instead of a statuscode, we return a ServiceActionStatus
Below you’ll see basic usage:

Using the above. The caller of the CarService just needs to Switch on the ServiceActionStatus and can easily handle, lots of different types of responses.

Showing messages to users with Toastr and SignalR, the perfect match.

Toastr
Sending updates/messages to users can sometimes be a pain in the butt, but using signalR can provide an enormous relief to exactly this matter.
Often times one would have a controller method which would return some sort of JsonResult (or View) containing whether or not the transaction went well. Using SignalR in conjunction with Toasts, we can write an a single implementation that will work for all of your future actions as well.
No more coding ajax success/failure for every single action.

Prerequisites:

  1. An MVC Project
  2. A BaseController
  3. SignalR package from nuget
    • Install-Package Microsoft.AspNet.SignalR
  4. A Toast implementation
    • //cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js
      //cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css
  5. A razor _layout

Once you have everything installed and up and running you are ready to implement SignalR

SignalR Backend implementation

Once the package is installed it should create a startup.cs file – if it doesn’t go create one.
It should look like this

Now we are ready to create the Hub. In SignalR the hub is what ties together connections and messages sent.

Once done, create a MessageEmitter – this will send Toasts through SignalR

Notice I’m using an enum for ToastType

Now we are about ready to send Toasts to our users.

SignalR Frontend implementation

Now for the razor layout page.
Standard SignalR connection and then showing the toast when it is received.

Using this whole ordeal

To actually send a toast message to the user.
simply call the BaseController method from earlier ShowToastMessage()

What now?

You could implement a GlobalErrorHandler attribute and a custom ToastException to throw on controller errors.
it could look something like this


it would then be used by throwing a new ErrorToast, which in turn would send an error HTTP status code (500) to the client AND show an error Toast.
You can now handle ajax errors, along with successes.

Documenting roles with swashbuckle

How to document attribute usage with swagger

You could basically document any attribute you have decorated your actions with, but this will focus mainly on documenting the role part of the Authorize attribute.
When using roles based authentication I like to document the roles in my swagger spec, this gives a nice indication, to the consumer, of which roles are required for different endpoints.
Here I have a basic Authorize attribute with a required role of “Admin”.

As with most other things swashbuckle related, we need to create an IOperationFilter

And that is it, you have now auto documented every role required across your API.
The swagger docs will look like the following.
BackupPortal_API

How to use the autogenerated swagger client

A detailed post on how to use an autogenerated swagger client

This blogpost will focus on the generated C# client.
To get started you basically just need 1 thing.

  1. A Swagger.Json file

Creating the client

If you already have the client you can skip this part
So you have created an API and added Swagger to it or you have been given a swagger.json file or someone else has created a swagger enable API or any combination of the above.
Now you want to create a client for, thankfully http://editor.swagger.io

Can generate a client for you.
Get your swagger.json file (if using swashbuckle the default url for the file is {your api domain}/swagger/docs/v1)
Go the http://editor.swagger.io

swaggerpaste
and paste the swagger.json file into the modal that pops up.
Note:
The editor should notify you of any errors in the schema
For this article I have used the swagger.json from the petstore example (any valid swagger will do).
If no errors arise, you are ready to generate the client.
swaggergenerateclient
Once the zip file is done downloading you should unzip and compile it using the Compile.bat file, located inside the folder.
Once compiled you can find the client and it’s dependencies inside the /bin folder.
Then just add the reference to a new project.
I will be using a basic Console Application.


Using the client

Note: The generated client has 2 dependencies namely; Newtonsoft.Json and RestSharp, these should be referenced through Nuget instead of using the ones that come with the client.
I will provide a basic run-through of how to use the client with different types of authentication, and how to use the generated client.
2 things to note about the client.

  1. All endpoints for the are located in the IO.Swagger.Api namespace
  2. All configuration options for the httpclient is located in the IO.Swagger.Client namespace
    This is where we will provide:

* Authentication
* Default Headers
* UserAgent
* etc.
3. All response models are location in the IO.Swagger.Model namespace
I will start with the configuration as this needs to be out of the way to call the API.

Client Configuration

Authentication:
The examples given are general examples and are not related to the petstore client (apart from the api naming).
I will go through 2 types of Authentication

  1. Basic Authentication
  2. APIKey authentication

Basic Authentication in the generated client is very straightforward

The above example will use the Authorization Header as transport with whatever scheme is defined in the swagger.json file.
Using an APIKey is almost as easy as Basic Authentication:
There are 2 configuration options for apiKey ApiKeyPrefix and ApiKey.
They are both directly related to the header that will be used as transport for the token.

In the above example we are using the Authorization Header as transport and we are using the Bearer Scheme (ApiKeyPrefix)
The sent header will look like the following: Authorization: Bearer {Some token value}

Endpoints

Using the endpoints is almost insanely easy. Every API endpoint is wrapped in a nice easy to use method, with input and output models.
The petstore API uses an api_key header with the value of “special-key” for authentication.
apikeyauth
The code for accessing the store inventory looks as the following

which generates the following output
clientoutput
The code for getting all pets with a particular status (to show the use of output models)

which generates the following output (as of this writing)
Petnames

End

This concludes the post, you should find that using the generated API is pretty straightforward and easy.

Handling Exceptions in WebApi globally

Handling exceptions can be such a hassle. Thankfully the WebAPI pipeline can help alot.
Utilizing the ExceptionFilterAttribute class can create
a consistent and simple way of returning great error responses for your API – like this

Lets get started.

First of all we need:

The Error Model:

The error interface:

We have 4 things here
1. ExceptionType – The type of error
2. A HttpStatusCode – Because returning the statuscode can prove useful to consumers
3. A Code – I use this for the httpstatuscode message
4. A List of Errors
1. Exception Type

Just an enum. I tend to use only Error, but it allows for a more gradient approach if needed.
2. HttpStatusCode
Thankfully the System.Net namespace provides most HttpStatusCodes as enum, so I just utilize this.
3. Code
I use this for the string interpretation of the httpStatusCode, but could be an internal code as well.
4. List of Errors

The above class consists of a Reason phrase and a message to go with this phrase
The “reasons” is also encapsulated as enums, but will be converted into their string representations in the inherited ApiException Class

The derived ApiException Class

Not alot to it. A few constructors, but it should explain itself pretty well.
“All of this is all good and fine, but how do we handle exceptions globally?” you ask.

The GlobalExceptionAttribute


it basically just checks which type of exception was thrown, and acts accordingly, notably typeof(ApiException). Any “unhandled” errors is thrown as “internal server error”. This is also where you would put any logging, as all exceptions will go through this filter. (I have left this out).
The above attribute should be applied in the WebApiConfig.cs file.

As you can see from the following part of the attribute

We check for any errors with typeof(ApiException), but we haven’t implemented the error type yet.
So in any Actions where you would normally return errors, you throw a new ApiException instead.

The above would cause our API to return a response, with a responsecode of 404 and the following body