Using ETag to cache responses in NancyFX

Caching data is usually a good idea, especially when creating APIs for mobile clients and the user may pay for each transferred byte. There are many approaches to caching data (I recommend reading this article), in my last NancyFX project I used ETag.


ETag is a HTTP header that acts as a hash of the data. When the server returns a response, it computes a hash of the data and sends it to the client. When the client requests the data again, it includes the ETag in its request. The server compares the ETag with the hash of the current data and if they match (the data did not change), it returns an empty responses with a HTTP 304 status code.

[Read More]
asp  azure  nancyfx 

NancyFX authentication for REST API

NancyFX is a great .NET framework well suited for creating REST APIs. There are many ways how to approach authentication, the simplest one is the good old Forms Authentication. The idea of Forms Authentication is that the user logs in with a username and password and gets a cookie, the protected endpoints then check the cookie. NancyFX supports Forms Authentication with the Nancy.Authentication.Forms package. The documentation describes how to use it on a web page, but to use it with a REST API a few changes are needed.

Forms Authentication differences for REST API

There are things you want to do differently in a REST API than on a web page. If a user tries to access a protected endpoint, the Forms Authentication on a normal web page redirects him to the login page. In REST API, you typically want the endpoint just to return HTTP 401, no redirects. Also, when a user successfully logs in, you just typically want to return HTTP 200, no redirects.

[Read More]

Returning files in NancyFX

In my current project, I have chosen NancyFx to implement a REST API. NancyFx is a .NET framework known for its “super-duper-happy-path“.

In one use case I generate a ZIP file in the temp folder and I want the API to return this ZIP file. NancyFx contains a Responses.AsFile helper but it works only with paths relative to the application.

If you have an absolute path of a file, you cannot use it. You need to create a StreamResponse and return the file as an attachment

var file = new FileStream(zipPath, FileMode.Open);
string fileName = //set a filename

var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName));
return response.AsAttachment(fileName);

[Read More]