You are making a GET
request and in case of GET
request there is no body only the URI. All the data you provide for the $.ajax()
call will be put into URI, for example your EDIT version will generate URI like this:
.../api/Values?value=%7B%22message%22%3A%22%5C%22Hello%20World%5C%22%22%7D
(notice that the JSON will be also URL encoded).
Now the URI parameters in Web API are being bind with use of ModelBinderParameterBinding
, which means that Web API will not use any MediaTypeFormatter
(which outputs complex types), but a ModelBinder
/ValueProvider
(which in this case will output a simple type - string).
You can approach your scenario by implementing custom ModelBinder
(remember to use proper classes and interfaces from ASP.NET Web API namespaces not ASP.NET MVC ones):
public class JsonModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == null)
return false;
bindingContext.Model = JsonConvert.DeserializeObject(valueProviderResult.AttemptedValue, bindingContext.ModelType);
return true;
}
}
public class JsonModelBinderProvider : ModelBinderProvider
{
public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
return new JsonModelBinder();
}
}
And attaching it to your parameter with ModelBinderAttribute
:
public IEnumerable<string> Get([ModelBinder(typeof(JsonModelBinderProvider))]CustomClass value)
{
return new string[] { "value1", "value2" };
}
You can find more details regarding the subject here: