Search code examples
c#asp.net-mvcmongodbwcfdatacontractserializer

Cannot expose mongodb objectId through wcf to mvc


I'm facing an annoying problem while providing a wcf service. I am familiar with wcf and its usage.

Service Implementation:

public class Service : IService
{
    public SampleClass SampleMethod ( SampleClass sampleParameter )
    {
        return new SampleClass { MyProperty1 = Guid.NewGuid(), MyProperty2 = ObjectId.GenerateNewId() };
    }
}

Service interface:

[ServiceContract]
public interface IService
{
    [OperationContract]
    SampleClass SampleMethod ( SampleClass sampleParameter );
}

And my contract class:

/// this class is in DataContracts dll - meantioned in the exception
[DataContract]
public class SampleClass
{
    [DataMember]
    public Guid MyProperty1 { get; set; }
    [DataMember]
    public ObjectId MyProperty2 { get; set; }
}

I keep the interface and the contracts in seperate library projects and use the dlls at the clients.

MVC Side calling of service:

static IService Service = new ChannelFactory<IService>(new BasicHttpBinding("regularBinding"), new EndpointAddress(BaseAddress + "Service.svc")).CreateChannel();

public ActionResult Index()
{
    var xyz = Service.SampleMethod(new SampleClass());
    return View();
}

I can call this service from my unit test project or from a desktop application. But when I call the service from an MVC application it throws ProtocolException:

An exception of type 'System.ServiceModel.ProtocolException' occurred in mscorlib.dll but was not handled in user code

Additional information: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:sampleParameter. The InnerException message was 'Error in line 1 position 451. 'EndElement' 'MyProperty2' from namespace 'http://schemas.datacontract.org/2004/07/DataContracts' is not expected. Expecting element '_increment'.'. Please see InnerException for more details.

I have a hunch that this is caused by some serializer related issue, but I don't really have deep understanding on those topics, so here I am.

What might be the cause of this behaviour? How can I overcome this without changing my data structures?

Update

Btw I realized that the exception occurs on return. When I throw an exception from within the service method, that exception propogates to the client. Therefore I can say my request with ObjectId can be received from the service but cannot return to the client.


Solution

  • We've found out the problem and the solution in the discussion with @jpgrassi, but since @jpgrassi is too humble to post the answer, here I am.

    Following the answer of this question @jeff's answer was inspiring enough to make me check the MongoDB.Bson dll's versions. There it was, they were different on server and mvc client and causing this problem. Leveling them on a version solved the problem.