I am having an issue with JSON deserialization of string values into C# properties of type object, they end up as an array of strings.
The value of foo.Bar in the Get and Post method is string[1]{"test"}, but I am expecting string "test".
I have tried attributing Foo with DataContract / DataMember, and JsonObject / JsonProperty attributes and get the same result.
Any idea why this is happening?
Here is my code from a empty Asp.net MVC3 Project. I installed the Microsoft.AspNet.WebApi RC nuget package version 4.0.20505.0 and jquery v 1.7.2
Update Updated code to include Get action and contentType: "application/json"
Global.asax
using System;
using System.Collections.Generic;
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "WebApi",
routeTemplate: "api/{controller}"
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
My Test Controller
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApiRCTest.Controllers
{
public class TestController : System.Web.Http.ApiController
{
public IEnumerable<string> Get([System.Web.Http.FromUri]Foo foo)
{
return new List<string>();
}
public void Post([System.Web.Http.FromBody]Foo foo)
{
object bar = foo.Bar;
}
}
public class Foo
{
public object Bar { get; set; }
}
}
My JavaScript
function post() {
$.ajax({
url: "http://localhost:55700/api/ApiTest/",
type: "GET",
dataType: "json",
accept: "application/json",
contentType: "application/json",
data: { Bar: "test" }
})
$.ajax({
url: "http://localhost:55700/api/Test/",
type: "POST",
dataType: "json",
accept: "application/json",
contentType: "application/json",
data: { Bar: "test" }
})
}