Ron Avraham
Ron Avraham

Reputation: 478

how to receive Dictionary in WebAPI from javascript json

I have this controller function in WebAPI:

public class EntityController : APIController
{
       [Route("Get")]
       public HttpResponseMessage Get([FromUri]Dictionary<string, string> dic)
       { ... }
}

and my request, in javascript, looks like this:

{
     "key1": "val1",
     "key2": "val2",
     "key3": "val3"
},

but the parse failed. is there a way to make this work without writing to much code? Thanks

my full request:

http://localhost/Exc/Get?dic={"key1":"val1"}

Upvotes: 1

Views: 1919

Answers (2)

D&#225;vid Moln&#225;r
D&#225;vid Moln&#225;r

Reputation: 11573

You could use a custom model binder:

public class DicModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(Dictionary<string, string>))
        {
            return false;
        }

        var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (val == null)
        {
            return false;
        }

        string key = val.RawValue as string;
        if (key == null)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type");
            return false;
        }

        string errorMessage;

        try
        {
            var jsonObj = JObject.Parse(key);
            bindingContext.Model = jsonObj.ToObject<Dictionary<string, string>>();
            return true;
        }
        catch (JsonException e)
        {
            errorMessage = e.Message;
        }

        bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value: " + errorMessage);
        return false;
    }
}

And then use it:

public class EntityController : APIController
{
    [Route("Get")]
    public HttpResponseMessage Get([ModelBinder(typeof(DicModelBinder))]Dictionary<string, string> dic)
    { ... }
}

In the ModelBinder I used the Newtonsoft.Json library to parse the input string, then converted it to Dictionary. You could implement a different parsing logic.

Upvotes: 4

user5447154
user5447154

Reputation:

See here ... with some adaptations to make. I think your difficulties are in how to call the URL.

Complex type is getting null in a ApiController parameter

Upvotes: 0

Related Questions