3

I have a Web API project which returns json objects. The objects are populated correctly, but when they are received by the calling application, they are empty. I suspect this is to do with Json being denied for GET requests.

My API controller code looks like this:

public IHttpActionResult GetThing(string id)
    {
        try
        {
            var model = new Thing(id);
            var res = Json<Thing>(model);
            return res;
        }
        catch
        {
            return NotFound();
        }
    }

At this point "res" is correctly populated. Now on the other (client) side I have:

internal static JsonResult GetThing(string thingId)
    {
        return GetTask<JsonResult>(string.Format(ThingUrl, thingId));
    }

When I check the value of the JsonObject here, it's empty (Data is null), but I also notice that the value of the field "JsonRequestBehavior" is "DenyGet" which I suspect is the issue.

My Question is, how do I set the value of this to be "AllowGet", so I can use the populated object? I'm losing what little hair I have left!

Faithypop
  • 183
  • 1
  • 2
  • 10

1 Answers1

3

You do not need to convert the object to JSON in the controller. You should be able to have your controller code look like this:

public Thing Get(string id)
{
    try
    {
        var model = new Thing(id);           
        return model;
    }
    catch
    {
        //throw not found exception
    }
}

Then when you make the request, ensure Accept: application/json header is set and you should be golden.

EDIT: Further to your comment, and with the code for actually making the request not visible, I can only assume that the code you have written to call the API endpoint must be incorrect.

It should look something like this:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("BaseUrlOfAPI");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    

    HttpResponseMessage response = await client.GetAsync("realtiveurltocontroller/thingid");
    if (response.IsSuccessStatusCode)
    {
        Thing thing = await response.Content.ReadAsAsync<Thing>();
        // Do whatever you want with thing.
    }
}

More information on this can be found here

David Watts
  • 2,135
  • 19
  • 30