Val
Val

Reputation: 1033

routing to MongoDB ObjectId via ServiceStack

I am developing a ServiceStack api and I am having trouble routing to:

    [BsonId]
    public ObjectId Id { get; set; }

I've tried setting up a custom binding model as follows:

  public class ObjectIdModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            return result == null ? ObjectId.Empty : ObjectId.Parse((string)result.ConvertTo(typeof(string)));
        }
    }


protected void Application_Start()
    {

        ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdModelBinder());

This is in the AppHost.cs

Routes .Add("/user") .Add("/user/{Id}");

When I tried to access the api through the url:

http://localhost:1000/api/user/1234567

I get the following error:

error Code RequestBindingException message Unable to bind request stack Trace at ServiceStack.WebHost.Endpoints.RestHandler.GetRequest(IHttpRequest httpReq, IRestPath restPath) at ServiceStack.WebHost.Endpoints.RestHandler.ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, String operationName)

Binding to a basic native type works, any idea how to fix something like this?

Upvotes: 2

Views: 375

Answers (1)

Val
Val

Reputation: 1033

passing a valid id such as '51cbda57d845130cc86322fd' instead of 1234567 correctly mapped it to the [Bson] Id property.

Upvotes: 1

Related Questions