Daniel Jo
Daniel Jo

Reputation: 350

Set mongodb ObjectId as an url parameter on web api 2.0

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?

Upvotes: 2

Views: 2153

Answers (2)

razon
razon

Reputation: 4050

For using ObjectId type in controller like this:

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

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

Upvotes: 1

Benjamin Soulier
Benjamin Soulier

Reputation: 2263

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);

Upvotes: 0

Related Questions