简体   繁体   English

使用NancyFx将实体框架对象返回为JSON

[英]Return Entity Framework objects as JSON with NancyFx

I'm building a small API (for read operations - GET) using NancyFX and C# with .NET 4.0 我正在使用NancyFX和C#和.NET 4.0构建一个小型API(用于读取操作-GET)

I'm using Entity Framework 6.0 in order to access a SQL Server 2008R2 database. 我正在使用Entity Framework 6.0来访问SQL Server 2008R2数据库。

I have the following route exposed with Nancy (this is just for testing purposes): 我在Nancy中公开了以下路线(这仅是出于测试目的):

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? 如何使用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. 我是Nancy的新手,我从今天早上才开始使用它。 It seems promising! 看来很有前途!

Thanks for the support. 感谢您的支持。

I found a solution for this case: 我找到了这种情况的解决方案:

I've changed the default Json Serializer that comes with Nancy with NewtonSoft.Json 我已经用NewtonSoft更改了Nancy附带的默认Json序列化器。

The code in ExampleNancyModule remains the same, however I've added a Boostrap file to overwrite the default behaviour of Nancy. ExampleNancyModule中的代码保持不变,但是我添加了一个Boostrap文件来覆盖Nancy的默认行为。 My Bootstrap.cs file looks like this: 我的Bootstrap.cs文件如下所示:

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. 有了这个,我可以得到一个尊重我的实体框架模型的属性和JSON配置的JSON响应。 Hope this helps someone else. 希望这对其他人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM