返回BsonDocument在ApiController [英] Return BsonDocument in ApiController

查看:537
本文介绍了返回BsonDocument在ApiController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的ASP.NET中的API MVC 4,我使用MongoDB的作为后端。

I'm working on an API in ASP.NET MVC 4, I'm using MongoDB as a backend.

由于MongoDB的存储和返回BSON对象,MVC4返回JSON对象,我想,这将是相当容易的,只需回报,其余来电BSON。

Due to MongoDB storing and returning BSON objects, and MVC4 returning JSON objects, I figured that it would be rather easy to simply return the BSON on the rest calls.

这没有工作,所以我发现了 .toJson()法日 BsonDocument 类,转换该BSON对象的JSON字符串,再presentation。不幸的是,当我通过返回此字符串我的 ApiController ,MVC显然认为它应该重新序列化字符串作为JSON,该浏览器不能跨preT。

This didn't work, so I found the .toJson() method on th BsonDocument class, converts the BSON object to a JSON-string representation. Unfortunately when I return this string through my ApiController, MVC apparently thinks it should re-serialize the string as JSON, which the browser can't interpret.

所以,我想问一下,如果有一种方法来禁用JSON序列的特定 ApiController 方法?

So I would like to ask if there is a way to disable the JSON serialization for a specific ApiController method?

我目前的解决方法是反序列化JSON返回以使其将再次序列之前,从 .toJson()回来了,但这似乎相当浪费。

My current workaround is to de-serialize the JSON returned from .toJson() before returning it such that it will be serialized again, but this seems rather wasteful.

推荐答案

presumably你与你的应用程序关联的架构和资源的API控制器试图返回。通过迫使它使用JSON,你是完全偏离主航道内容协商忽略了许多的WebAPI的好处。如果你的客户想XML或YAML或...

Presumably you have a schema associated with your application and the resource your api controller is attempting to return. By forcing it to use json, you are ignoring many of the benefits of the WebApi by completely sidestepping content negotiation. What if your client wants xml or yaml or ...

您所遇到的问题是,的WebAPI不知道如何序列化BsonDocument。所以,你可以为它,这样它知道如何处理它写ModelBinder的。另外,和影射我的第一段,创建强类型实体/资源类和因为两者的MongoDB和的WebAPI已经了解这些类型,他们将能够在本机与他们一起工作。

The issue you are experiencing is that WebApi doesn't know how to serialize a BsonDocument. So, you could write a ModelBinder for it such that it knows how to deal with it. Alternatively, and alluding to my first paragraph, create strongly typed entity/resource classes and since both MongoDB and WebApi already know about these types, they'll be able to work with them natively.

这篇关于返回BsonDocument在ApiController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆