Sinan
Sinan

Reputation: 908

Send mongodb filter string threw http to the web api

I am looking a way to send a mongodb filter from the webapp threw http to the web api.

In the webapp controller: serialize or deserialize then Encrypt

var filter = Builder<BsonDocument>.filter.Eq("firstName", "Foo");

In the web api controller: Decrypt, serialize or deserialize

The logic between is working.

Should I receive it as a query in the web api controller

    [HttpGet]
    public async Task<IActionResult> GetByQuery([FromQuery] string filter)
    {
    }

I am not sure how to send the mongodb filter, I did some research but still not able to make it work.

I hope is clear! Thanks

Mongodb 2.4.4
Asp.net core 2.0

Update
What I am try to do is for example:
http://localhost:12345/api/v1/monsters/ "the mongodb filter here"
or
http://localhost:12345/api/v1/monsters?filter= "mongodb filter here as query string"

How to or what I have to do and what is the best way to send a MongoDB filter. Should I have a filterdefinition and serialized to json or vice versa, I am looking for the best approach.

Upvotes: 0

Views: 905

Answers (1)

Jaybird
Jaybird

Reputation: 541

To get the URL, I had to check MongoDB Json Generation.

var json = filter.Render(BsonDocumentSerializer.Instance, BsonSerializer.SerializerRegistry).ToString();
var url = $"http://localhost:12345/api/v1/monsters?filter={WebUtility.UrlEncode(json)}";

Then in your API:

var mongoFilter = (FilterDefinition<BsonDocument>)WebUtility.UrlDecode(filter);

To answer your question of whether this is the best approach, I might need to know a bit more about your application architecture and the complexity of your application.

Upvotes: 1

Related Questions