NancyFX + CORS

Every once in a while you need to have access to a json api from another domain.

Thankfully there’s a mechanism to allow this. This Mechanism is called CORS

So before any JSON request is allowed a Options requst will be sent to the corresponding ressource and expects a „Access-Control-Allow-Origin“ header to be present.

There can be different values set for this which is explained in the linked article.

To enable this globally for a NancyFX Module you have to put the following code into it.

// allow CORS
Options["/{catchAll*}"] = parameters =>
{
	return new Response { StatusCode = HttpStatusCode.Accepted };
};

After += (Context) =>
{
    Context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    Context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
    Context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Authorization, Accept, Origin");
};

Hopefully this will help some folks out there

Kommentar verfassen

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.