2

I want to pass a mongodb ObjectId parameter to controller via the URL as string.

I know in MVC you can use ModelBinder.

How I can do that in ASP.NET WebApi 2.0?

razon
  • 3,882
  • 2
  • 33
  • 46
Daniel Jo
  • 340
  • 2
  • 14

2 Answers2

1

For using ObjectId type in controller like this:

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

see my answer: https://stackoverflow.com/a/47107413/908936

razon
  • 3,882
  • 2
  • 33
  • 46
0

ASP.NET Web API has the same detault route principle as MVC.

To be able to pass a value that is mapped directly then to your parameter, just match the property in query string to your method parameter name:

Call done to: {yourserver}/api/valuesasparam/call?myparam=498574395734958

Your ApiController:

public class ValuesAsParamController : ApiController
{
    [HttpGet]
    public IEnumerable<string> Call(string myparam)
    {
        // Do something with your 'myparam' value
    }
}

Update:

If you will to get directly the value as an ObjectId, check here for Model binding. and the follwing code to convert your string to an ObjectId:

MongoDB.Bson.ObjectId.Parse(myparam);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Benjamin Soulier
  • 2,223
  • 1
  • 18
  • 30
  • I don't want to convert the parameter in the controller, I want to set the parameter as ObjectId and it will automatically convert the string to ObjectId – Daniel Jo Aug 31 '16 at 10:19
  • The way to do it is to bulid up a ModelBinder to transform the string to ObjectId, check my post update – Benjamin Soulier Aug 31 '16 at 10:24
  • 1
    [here](https://stackoverflow.com/questions/10942824/mvc4-webapi-serialization-deserialization-mongodb-objectid) is another **simple solution**. hope helps someone. – Shaiju T Aug 07 '17 at 08:03