How to pass ObjectId from MongoDB in MVC.net

后端 未结 5 458
野的像风
野的像风 2020-12-06 11:55

I\'m starting a new project with Mongo, NoRM and MVC .Net.

Before I was using FluentNHibernate so my IDs were integer, now my IDs are ObjectId. So when I have an Edi

5条回答
  •  太阳男子
    2020-12-06 12:44

    For Web API you can add Custom parameter binding ule in WebApiConfig:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //...
            config.ParameterBindingRules.Insert(0, GetCustomParameterBinding);
            //...
        }
    
        public static HttpParameterBinding GetCustomParameterBinding(HttpParameterDescriptor descriptor)
        {
            if (descriptor.ParameterType == typeof(ObjectId))
            {
                return new ObjectIdParameterBinding(descriptor);
            }
            // any other types, let the default parameter binding handle
            return null;
        }
    
        public class ObjectIdParameterBinding : HttpParameterBinding
        {
            public ObjectIdParameterBinding(HttpParameterDescriptor desc)
                : base(desc)
            {
            }
    
            public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
            {
                try
                {
                    SetValue(actionContext, new ObjectId(actionContext.ControllerContext.RouteData.Values[Descriptor.ParameterName] as string));
                    return Task.CompletedTask;
                }
                catch (FormatException)
                {
                    throw new BadRequestException("Invalid ObjectId format");
                }
            }
        }
    }
    

    And use it Without any additional attributes in controller:

     [Route("{id}")]
     public IHttpActionResult Get(ObjectId id)
    

提交回复
热议问题