Reputation: 739
I'm building a small API (for read operations - GET) using NancyFX and C# with .NET 4.0
I'm using Entity Framework 6.0 in order to access a SQL Server 2008R2 database.
I have the following route exposed with Nancy (this is just for testing purposes):
public ExampleNancyModule()
{
Get["/v1/address_types"] = parameters =>
{
var address_types = context.address_type.First();
return Response.AsJson(address_types);
};
}
I'm able to access the route with Postman, however I'm receiving an empty response body. How can I return the object and/or a list of objects with Nancy?
I guess there's more configuration that needs to be done first. I'm new with Nancy, I just started using it this morning. It seems promising!
Thanks for the support.
Upvotes: 1
Views: 1773
Reputation: 739
I found a solution for this case:
I've changed the default Json Serializer that comes with Nancy with NewtonSoft.Json
The code in ExampleNancyModule remains the same, however I've added a Boostrap file to overwrite the default behaviour of Nancy. My Bootstrap.cs file looks like this:
namespace MyProject
{
public class Bootstrap : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
container.Register<JsonSerializer, CustomJsonSerializer>();
}
}
public class CustomJsonSerializer : JsonSerializer
{
public CustomJsonSerializer()
{
this.ContractResolver = new CamelCasePropertyNamesContractResolver();
this.Formatting = Formatting.Indented;
}
}
}
With this I can get a JSON response that respects the attributes and the JSON configuration of my Entity Framework Models. Hope this helps someone else.
Upvotes: 4