【问题标题】:ASP.NET Web Api RC: JSON deserialization into object propertiesASP.NET Web Api RC:将 JSON 反序列化为对象属性
【发布时间】:2013-05-28 22:48:13
【问题描述】:

我在将字符串值 JSON 反序列化为对象类型的 C# 属性时遇到问题,它们最终成为字符串数组。

Get 和 Post 方法中foo.Bar 的值是string[1]{"test"},但我期待的是字符串"test"

我曾尝试使用DataContract / DataMemberJsonObject / JsonProperty 属性将Foo 归因并得到相同的结果。

知道为什么会这样吗?

这是我在一个空的 Asp.net MVC3 项目中的代码。 我安装了 Microsoft.AspNet.WebApi RC nuget 包版本 4.0.20505.0 和 jquery v 1.7.2

更新 更新的代码包括 Get action 和 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);            
    }
}

我的测试控制器

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" }
    })
}   

【问题讨论】:

    标签: json.net asp.net-web-api


    【解决方案1】:

    这实际上是发送“application/x-www-form-urlencoded”,而不是 JSON。试试:

        $.ajax({
        url: "http://localhost:55700/api/Test/",
        type: "POST",
        dataType: 'json',
        contentType: 'application/json',
        accept: "application/json",
        data: JSON.stringify({ Bar: "test" })
    

    【讨论】:

    • 添加内容类型会导致Post Action中的Foo为null,对Get Action没有影响,同样会获取一个字符串数组到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”。
    【解决方案2】:

    我也遇到了这个问题——我创建了一个名为 JsonFromUri 的简单属性,它基本上可以实现它所说的。您可以从 nuget 获取或在此处自行查看:

    https://github.com/itsdrewmiller/JsonFromUri

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多