1

ASP.NET MCV4とMongoDBはかなり新しく、WebAPIを構築しようとしています。私はついにそれを正しく理解したと思いましたが、アプリを起動して次のように入力http://localhost:50491/api/documentすると、ブラウザにこのエラーメッセージが表示されます

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

これが私のコードです

これはドキュメントクラスです

public class Document
{
    [BsonId]
    public ObjectId DocumentID { get; set; }

    public IList<string> allDocs { get; set; }
}

これは、DBへの接続が行われる場所です。

public class MongoConnectionHelper
{
    public MongoCollection<BsonDocument> collection { get; private set; }

    public MongoConnectionHelper()
    {
        string connectionString = "mongodb://127.0.0.1";
        var server = MongoServer.Create(connectionString);

        if (server.State == MongoServerState.Disconnected)
        {
            server.Connect();
        }

        var conn = server.GetDatabase("cord");

        collection = conn.GetCollection("Mappings");  
    }

ApiControllerクラスは次のとおりです。

public class DocumentController : ApiController
{
    public readonly MongoConnectionHelper docs;

    public DocumentController()
    {
        docs = new MongoConnectionHelper();
    }

    public IList<BsonDocument> getAllDocs()
    {
        var alldocs = (docs.collection.FindAll().ToList());
        return alldocs;

    }

}

さらに読み進めると、エラーメッセージが表示されます。

Type 'MongoDB.Bson.BsonObjectId' with data contract name 'BsonObjectId:http://schemas.datacontract.org/2004/07/MongoDB.Bson' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

それはすべて良いことですが、どうすればよいですか?

4

2 に答える 2

2

a)Web APIを介してドキュメントクラスをシリアル化せず、シリアル化することを目的としたいくつかのDTOを作成するか、b)IDとして他のものを使用します。

簡単に自動生成されたIDが必要で、それがわずかに多くのスペースを消費するという事実に問題がない場合は、次の「ハック」に頼ることができます。

public class Document
{
    public Document()
    {
        Id = ObjectId.GenerateNewId().ToString();
    }

    public string Id { get; set; }
}

このようにして、MongoIDを取得しますが、それらは文字列として保存されます。

于 2013-01-10T13:29:44.157 に答える
0

XML形式のWebAPI2応答が必要な場合は、以下のようなデフォルトのIDを処理する必要があります。

例:ObjectId( "507f191e810c19729de860ea")

シリアル化からIDを削除する必要があります。

[DataContract]
public class Document
{
    [BsonId]
    public string Id { get; set; }
    [DataMember]
    public string Title { get; set; } //other properties you use
}

または、カスタムロジックを使用してIDのタイプを変更できます

public class GuidIdGenerator : IIdGenerator
{
    public object GenerateId(object container, object document)
    {
        return  Guid.NewGuid();
    }

    public bool IsEmpty(object id)
    {
        return string.IsNullOrEmpty(id.ToString());
    }
}

public class Document
{
    [BsonId(IdGenerator = typeof(GuidIdGenerator))]
    public string Id { get; set; }
    public string Title { get; set; } //other properties you use
}
于 2017-08-04T07:29:11.127 に答える