我有一個JSON反串行化字符串值到類型對象的C#屬性的問題,他們最終成爲一個字符串數組。ASP.NET Web Api RC:JSON反序列化到對象屬性
Get和Post方法中foo.Bar
的值是string[1]{"test"}
,但我期望字符串爲"test"
。
我試着用Foo賦予DataContract
/DataMember
和JsonObject
/JsonProperty
屬性並得到相同的結果。
任何想法爲什麼會發生這種情況?
這是我從一個空的Asp.net MVC3項目的代碼。 我安裝了Microsoft.AspNet.WebApi RC NuGet包4.0.20505.0版本和jQuery 1.7.2 v
更新 更新代碼,包括獲取和行動的contentType: 「應用/ 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);
}
}
我的測試控制器
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; }
}
}
我的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" }
})
}
添加內容類型使美孚是在POST操作空和對我們採取行動,這也得到一個字符串數組沒有影響進入foo.Bar –
對於JSON,您需要調用JSON.stringify()。否則,jQuery會將其序列化爲form-urlencoded(「Bar = test」) –
Web API對JSON和form-urlencoded(application/x-www-form-urlencoded)使用不同的格式化程序。我不知道爲什麼form-urlencoded的情況下將Bar屬性反序列化爲一個數組。 JSON格式化程序可以處理匿名類型。 此外,對於GET請求,數據被編碼到URI查詢字符串中,所以它不是JSON,並且在這種情況下具有內容類型是沒有意義的。該URI將是「/ api/Test /?Bar = test」。 –