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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

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
The way to do it is to bulid up a ModelBinder to transform the string to ObjectId, check my post update
here is another simple solution. hope helps someone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.