Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API - JObject from URI

Web API allows me to capture the body of a POST request in a JObject:

    $.post('/api/Query/DoSomething', { Foo: "one", Bar: 4 });

    public string Post(JObject data)
    {
        // data is populated
    }

However the same technique does not work with a get request and URI parameters.

    $.get('/api/Controller', { Foo : "one", Bar : 4 });

    public string Get([FromUri]JObject data)
    {
        // data is empty

    }

Any workaround here?

like image 337
Shaun Rowan Avatar asked Dec 01 '25 05:12

Shaun Rowan


1 Answers

It doesn't work because a GET request does not have a body, and hence no content type. Therefore, Web API does not know that you have JSON in your URL. You have a few choices:

  1. Pass your data as query string parameters, as is traditionally done in GET requests, and change your method to accept those parameters individually, or in a regular class (POCO).
  2. Change your GET method to accept a string instead of a JObject, then use JSON.Net to deserialize it manually, e.g. JObject obj = JObject.Parse(data);
  3. If you're feeling ambitious, you might be able to implement a custom binder to do this.

My recommendation is option 1. Traditionally, a GET method is just intended to look something up, so you really should only be passing IDs and simple query options anyway. It is unusual to be passing JSON data in a URL. Also the length of URLs can be limited by some browsers. If you find you are needing to pass JSON data, use POST (or PUT) instead.

like image 134
Brian Rogers Avatar answered Dec 05 '25 01:12

Brian Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!