ASP.NET Core Embedded Resource

ASP.NET Core Embedded ResourcesIn my previous blog about adding gzip compression when using NancyFX, I wanted to test the compression by outputting a large json data file in one of my endpoints.

At first I was just going to generate some random data and serialize it at runtime but then I found Mockaroo, which provided a small dataset of random data that I could download.

So now that I had this generated file, I  wanted to include the file in my project as an embedded resource in which would be read and at returned as output.


The project.json file is new to ASP.NET Core, which defines project information and dependencies, similar to the combination of a web.config, csproj files, package.config is in ASP.NET 4.

There is a resource section in the project.json which is for adding resources to your assemblies as embedded resources.  The values are relative to the project.json file itself and allows you to specify glob patterns (wildcards).

In my demo project, I had a fakedata.json file which resides in the same path as the project.json file.  Here is my project.json file, including the new resource section.


All of your resources will be included in the assembly when built.  You can read those resources by getting a stream of the resource.


If you use a glob in your resource path to possibly include all files within a directory, but want to exclude specific files, you can do so with the resourceExclude.


If you are looking for more information about the project.json, I’d recommend taking a look at the GitHub wiki.  The docs are helpful but I couldn’t find a ton of info the project.json file specifically (yet).  I assume the docs will improve over time and they are a work in progress.

Read More

Gzip Compression with NancyFX

Gzip compressionI was looking at the size of the payloads in my web api and thought it would be worth investigating if adding HTTP compression via gzip would be worthwhile.

After a quick search, I found a post by Simon Cropp back from 2011.  This was a good starting point, however how you wired it up with Nancy current day (1.4.3) is a bit different.


I’ve basically taken Simon’s code and added it to a new class that implements IApplicationStartup.

There are a few checks that occur before compressing the output.

  • Does the incoming request accept header contain gzip?
  • Is the outgoing HTTP status code 200?
  • Is return content type compatible?  In my example, I’m only checking for application/json.
  • Is return content length large enough?

If all are true, then the output is compressed.

Wiring Up

One reason I really love Nancy is how it scans assemblies looking for implementations of interfaces.  This makes it so seamless to add functionality.

Adding this class to your project is all you need to do.  Seriously.  This is indeed the super-duper-happy-path.

You can also hook into the pipeline via the bootstrapper, I just happened to prefer creating a class that implements the IApplicationStartup as I can easily reuse it by dropping it into other projects.


In my demo project, I’ve added a a json file with generated data.  I’m output this file at the endpoint /nancy/gziptest.

Without gzip


With gzip


Source Codegithub-octocat

The source code for this demo is available on Github.



Read More

Nancy.Linker: NancyFX URI Builder

NancyFXIf you are using NancyFX, likely at some point you needed to generate a URI of another route in your application.

When I first ran into this problem, I was looking for some type of built-in URI builder, similar to what you would do with ASP.NET MVC’s Url.Action().


Luckily, I found Nancy.Linker by Christian Horsdal.

Simple URI builder for named Nancy routes with optional pass through of query parameters.

It’s really that simple.  What it allows you to do is generate URI’s based on the names given to your routes.

If you are not naming your routes yet, you will need to do so.  This is fairly straightfowrad, and you really only need to do it if you need to use the linker.


First thing we need to do is acquire the Nancy.Linker package:

PM> Install-Package Nancy.Linker

Now here is an example of an route without a defined name:

To give this route a name, simply supply it as the first argument of the route builder.

In order to build a URI, we must take a dependency on IResourceLinker in our Nancy Module.   I was unable to have IResourceLinker automatically register with my container, so  I’ve registered it in my Boostrapper.

Now we we can generate a URI to a named route.

In my example, I’m going to create another route that is simply going to return the URI of our existing route named “HelloWorldRoute”.

Now if we access http://localhost:5000/findhelloworld via Postman, our results as expected.


Route Parameters

Often your routes will have parameters in which you will need to pass to the linker.  I will modify the above example to include a string route parameter.

Source Codegithub-octocat

The source code for this demo is available on Github.

Read More

ASP.NET 5 is now ASP.NET Core 1.0


Yesterday it was announced on the ASP.NET Community Standup by Damian Edwards and on Scott Hanselman’s blog that Microsoft has decided to rename ASP.NET 5 (also formerly known as ASP.NET vNext) to ASP.NET Core 1.0.

Reset Major Version Number

As many in the community, I view this rename prior to the RTM as a good thing.  ASP.NET 5 was a very confusing name as it is a completely new version of ASP.NET.  I welcome the reset to 1.0 as it gives a better description that this is indeed a rewrite and ground up work.

Also, frameworks such as Entity Framework had also had an identity crisis as they also were just incrementing the major version number, even though they are completely new as well.  Because of this, Entity Framwork 7 is now being renamed to Entity Framework Core 1.0


I’m still unsure about how I feel about adding the word “Core” to the framework name.  My main concerns are:

Google Juice

How does this affect searching and Google results?  Searching and when creating content that will be indexed must include the word “Core” and possibly the version number.

Version number may not be an issue as there won’t likely be an overlap in somewhat current/useful version numbers.  Eg, Entity Framework 5 vs Entity Framework Core 5.


This is a rewrite.  As Steve Smith blogged with the history and meaning behind ASP and ASP.NET, it may not seem valid anymore to call it Active Server Pages.

I do think the perception of Microsoft and it’s association to .NET is changing (for the better?) to developers not currently using .NET.  However, I do believe there is a stigma associated ASP.NET in these other communities.

I’m all about welcoming more developers, junior and seasoned, to the .NET ecosystem.  I would think ditching the ASP.NET name altogether might of helped in that direction more.

I am also aware of how much effort has been put into the ASP.NET brand, and you aren’t going to just throw that away, even if it may not have the best perception.


I’m happy with this decision.  Would I of preferred “Some Short Googleable Name” 1.0? I think so.  But ASP.NET Core 1.0 is much better than ASP.NET 5.

I do think there will still be some lingering confusion since the name ASP.NET 5 has been living for a bit, but with due time it will be water under the bridge.


Read More

ASP.NET Core Series: NancyFX

ASP.NET 5 NancyFXLast week I decided to start migrating one of my existing ASP.NET application that uses NancyFX over to ASP.NET Core.  The process is actually pretty straight forward if you are familiar with OWIN.


OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.

To clarify and reword slightly, OWIN is a open source specification that is not defined by Microsoft and is not an actual implementation.

ASP.NET Core supports OWIN and defines middleware to be used in a  request pipeline with the Microsoft.AspNet.Owin package.

ASP.NET Core NancyFX Demo

All of the source code for this demo is available on GitHub.

The first thing we are going to do for this demo is add the appropriate nuget packages.

Note: At the time of this post, ASP.NET Core is curently at RC1, which is still a pre-release and therfore you will need to include the “-Pre” option when installing any pre-release packages.

PM> Install-Package Microsoft.AspNet.Owin -Pre

PM> Install-Package Nancy

PM> Install-Package Nancy.Owin

Now in our Configuration method of our Startup class, there is a new extension method of UseOwin provided by the Microsoft.Asp.Net.Owin package, which allows us to include additional OWIN compatible middleware to our ASP.NET Core pipeline.

The Nancy.Owin package also provides an extension method UseNancy that we can use inside our UseOwn method.

For the demo, I’ve created a simple Nancy Module.  Since Nancy will find it automatically (which is really nice) there is no registration needed.

Nancy does not support targeting .NET Core however does support Mono.  You will have to remove the “dnxcore50” from frameworks section of the project.json

At this point, you are ready to run the demo.  Your application should be hosted on port 5000.  Calling http://localhost:5000/nancy/demo using Postman produces the expected output.


Owin Performance

The ASP.NET Core documentation notes that you should not use multiple calls to UseOwin.  Rather, insert all of your OWIN middleware grouped together within one UseOwin call.

Source Codegithub-octocat

The source code for this demo is available on Github.

ASP.NET Core Series

Read More

ASP.NET Core Series: The Basics

ASP.NET 5I’ve been wanting to create a ASP.NET Core Overview and series of blog posts on ASP.NET Core, but due to the number of betas and changes that came with those, I decided to hold off.

Although ASP.NET at the time of this post is still at RC1 (update 1) and not RTM yet, there likely may be some naming changes.  Still, I think we are at a stable enough point where you can take this series and get a good feeling about where ASP.NET currently stands and how you get started writing your own apps.


This series will focus on development of ASP.NET Core applications using:


ASP.NET Core is a new open-source and cross-platform framework for developing web applications in .NET.  It is a totally new version of ASP.NET built from the ground up.

Getting things straight

Before we jump to installation and getting a new project setup, I think it’s important to define some the pieces to the puzzle, as I was pretty confused early on.  Even if you are familiar with ASP.NET 4 and are using MVC or WebAPI now, a lot has changed.

.NET Execution Environment (DNX)

The DNX is a SDK and Runtime environment that enables you to build and run .NET applications cross platform (Windows, Linux, and Mac).  It does so by providing a standard execution environment across different flavors of .NET.  Flavors?  Yes. Flavors.

If you are primarily currently running and developing in Windows, then you are using the full “.NET Framework”.  However, you can also target Mono or .NET Core


Mono is an open source port of the .NET Framework sponsored by Xamarin.  Beyond the runtime environment supported by the DNX, it also includes a C# complier and Base Class Libraries compatible with the full .NET Framework.

.NET Core

Similar to Mono, this is a new open source runtime (CoreCLR) and libraries (CoreFX) that is cross platform.    The main benefit to .NET Core because of its modularity, is the ability to deploy and run a .NET Core application on a target host without the need to have the .NET Framework installed.  This also allows you to run different applications targeting different runtimes on the same host side by side.


I do believe there has been a bigger push by Microsoft and the community (hence this post) to reach out to developers that live in other ecosystems to advocate the use of .NET and ASP.NET Core.

With Visual Studio Code and Omnisharp, there is now a legitimate effort being put forward to create cross platform tooling outside of Windows where you can developg .NET and ASP.NET Core applications.

There is also a lot of effort being put into giving developers a incredibly easy path to being developing using ASP.NET Core applications.

Previously, if you were going to write an application in .NET, you had almost no options.  Your tooling was forced to Windows and Visual Studio.  This is no longer becoming the case.  It seems the new motto is build anywhere, run anywhere.

Next Up

Next post will be taking a look at DNX a bit more in detail, how to install, and how to create a new DNX Project.

Read More

NancyFX: .NET Web Framework

NancyFXWorking in the .NET ecosystem can feel very insular.  Especially if you work in the enterprise.  At the very beginning of my career in software development (circa late ’90s), I was generally using more open tooling and languages.  The atmosphere in those communities had (past tense) a much different feeling than it does in the .NET community.

Most developers that are in .NET can feel the changes that have been occurring recently.  There has been a bigger wave of alternative and open source software awareness within .NET.  However, I still don’t think that the .NET community at large are even aware of some of the great open source libraries and frameworks.

 ASP.NET MVC / Web Api

If you were starting new web project in .NET, I think it’s safe to say that most would automatically choose ASP.NET MVC or Web Api.  There may be legitimate reasons for doing so, such as you or your team having exiting knowledge of those frameworks.

However, NancyFX is a great alternative that is very mature, simple and has great documentation.


Nancy is a lightweight web framework.  It’s really that simple.

At its heart it provides a really easy way to create HTTP services.  That means you could be generating and returning HTML using the MVC pattern or creating services returning JSON.  You are not forced into either or into any heavy configuration. You are simply creating endpoints using HTTP verbs.

Getting Started

In my code examples, I’m going to be using my Self Host ASP.NET Demo application, which is currently demos how to use Katana (Owin) Self Host, Middleware, File Server and Topshelf.

I’m going to extend this project to include Nancy.

First let’s install Nancy from Nuget

Install-Package Nancy

For my example, I’m also going to need to Install the Nancy.Owin Package because my self host application uses the Katanta Owin Implementation with HttpListener.

Install-Package Nancy.Owin

Now that we have our packages installed, in your Startup class, use the new IAppBuilder.UseNancy() extension method.

Simplest Example

My intent for this blog post is simply to get people looking at Nancy as an alternative.  I can’t show you all all the wonderful features in one easy to digest post.  In posts to come I’m going to cover many different topics related to Nancy.  However, for this post I want to provide the simplest possible example of creating an HTTP endpoint using the GET verb.

Similar to ASP.NET MVC or Web Api, you will create a class that extends another.  For Nancy, we create a class that extends the NancyModule.  It is in this class were we define the routes and the endpoint implementation.   In my example above, I’ve created a HTTP GET route to /nancy/demo.  Since my self host application is running on localhost:8080, this translates to http://localhost:8080/nancy/demo.

Here are the results:


As you might expect, Nancy has automatically converted my .NET string array to JSON without any configuration.


As I mentioned, I plan on going over in detail many features of Nancy and why you may want to use it.  But to get you interested a bit more, here are a few key points.

  • Model Binding
  • Built in IoC Container (Support for almost all others)
  • Easy Testing
  • Content Negotiation
  • View Engines (including Razor Support)
  • Multiple Hosting Options (Katana/Owin, ASP.NET HttpHandler, more)
  • Mono Support

Please take a few moments and check out the great docs over on Github.

Source Code

GithubThe source code for this demo is available on Github.

OWIN/Katana Series

If you want more information about OWIN/Katana, please take a look at my other series of posts.

  1. How to Self Host ASP.NET Web Api

  2. Self Host ASP.NET Web Api as a Windows Service

  3. ASP.NET Self Host Static File Server

  4. How to create Katana Middleware

Read More

How-To Create Katana Middleware

PipelineWhat I love about Katana (OWIN Implementation) is the ability to add functionality through the request pipeline.  In this post I’m going to extend my ASP.NET Self Host Web Api application by demonstrating how you can create your own Katana Middleware.

What’s OWIN Middleware?

OWIN specification defines middleware as:

Middleware – Pass through components that form a pipeline between a server and application to inspect, route, or modify request and response messages for a specific purpose.

Katana IAppBuilder.Use

There are couple different ways you can create your own middleware.  The simplest is to call the IAppBuild.Use method in your Startup class.

For our example, we are going to add a Product to the response header.

context is of type IOwinContextnext is of Func<Task>

IOwinContext contains the Request, Response, Environment and other properties you can access to manipulate the request or response.

Middleware Type

Another way to create middlware is by creating your own class that extends and overrides the OwinMiddleware base class.

For this example, we are going to add a MachieName to the response header.

In order to include our new middleware class into the pipleline, you must call the IAppBuilder.Use in your Startup class, but this time specifying the type of our class.

Notice we aren’t passing an instance of our CustomMiddlware but just the type.

Startup Class

After adding our two new middlware that are adding headers to the response, here is what our Startup class now looks like.

Now when I run the application and make a HTTP call to http://localhost:8080, the headers returned are:


Source Code

GithubThe source code for this demo is available on Github.

OWIN/Katana Series

If you want more information about OWIN/Katana, please take a look at my other series of posts.

  1. How to Self Host ASP.NET Web Api

  2. Self Host ASP.NET Web Api as a Windows Service

  3. ASP.NET Self Host Static File Server

Read More

ASP.NET Self Host Static File Server

Continuing in my Owin and Katana series of blog posts, I’m going to demo an ASP.NET Self Host Static File Server. If you have not seen my previous posts in this series, I’ve covered how to self host a Web Api application and how to use Topshelf to debug and run as a windows service.

The wonderful thing about the shift to Owin and Katana with ASP.NET is middleware.

Katana has a file server implementation that you can plugin to your application startup pipeline in order to serve static files either on a filesystem or from embedded resources.


The first thing we will do with our demo application is install the Owin StaticFiles middlware into our project.

Install-Package Microsoft.Owin.StaticFiles

The simplest possible configuration is to call IAppBuilder.UseFileServer(true).  This will enable directory browsing of files from the current location of the executable.

When running our demo application, this results in showing us the directory listing when we pass thru our Web API routes without a match.


Now this isn’t very useful but it displays the simplicity of different Owin middlewares that are available.

UseFileServer has several different overloads:

Name Description
System_CAPS_pubmethodSystem_CAPS_static UseFileServer(IAppBuilder)

Enable all static file middleware (except directory browsing) for the current request path in the current directory.

System_CAPS_pubmethodSystem_CAPS_static UseFileServer(IAppBuilder, Boolean)

Enable all static file middleware on for the current request path in the current directory.

System_CAPS_pubmethodSystem_CAPS_static UseFileServer(IAppBuilder, FileServerOptions)

Enable all static file middleware with the given options

System_CAPS_pubmethodSystem_CAPS_static UseFileServer(IAppBuilder, String)

Enables all static file middleware (except directory browsing) for the given request path from the directory of the same name

For our demo application, we are going to create our File Server to serve files from an Assets directory that lives in the same location as our executable.

Now when we browse we see the files within the Assets directory.


Content Type Provider

The Katana FileServer only serves known content types.  If you try and browse to a file that is not a known content type, it will return a 404.

In my example above, I’ve added a data.json file.  Odd to me was that a json file is not a known content type.  In order to serve json files, we must create our own content type provider and add our mappings.

Now we need to specify our CustomContentProvider in our FileServerOptions.

Source Code

GithubThe source code for this demo is available on Github.

Read More

Self Host ASP.NET Web Api as a Windows Service

In my previous blog I demonstrated how to Self Host ASP.NET Web API, which was a very basic console application leveraging Owin and Katana.

The next step in this series is how to turn your console application into a Windows service.

Windows Service Template

The typical way to create a Windows Service is by using the Windows Service template when creating a new project within Visual Studio.

The template will create a Program.cs calling ServiceBase.Run() in the Main() method.

SelfHostServiceBase is the code that will extend ServiceBase.   You would have to implement OnStart() and OnStop()

That’s simplest possible implementation.  Now when you start debugging, you are treated with this wonderful message.


What this means is you must build your Windows service, start it, then attach the debugger to the process.

Doesn’t sound like a fun way to debug does it?


TopshelfThere is a great open source project called Topshelf which allows you to create a windows service which is much easier to debug.

Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.

First thing is to install Topshelf into your project via nuget.

Install-Package Topshelf

Next we need a tiny bit of code to configure our service with topshelf.

We tell topself which class will contain our service (TopselfService) as well as which method to call when the service starts and stops.

Also, you can define which user the service should run as, as well as the name, display name and description.

Now when you debug the application, it will run just like a Console application, in which you can add breakpoints and debug.

Self Host ASP.NET Web API

To verify my web api application is responding, here is the result from my Postman call



Source Code

GithubThe source code for this demo is available on Github.


Next up I’ll continue adding to the demo by serving static assets from your self host application.

Read More