2

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

foo.BarGet 和 Post 方法中的值是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"

全球.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" }
    })
}   
4

2 回答 2

3

这实际上是发送“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" })
于 2012-06-15T22:52:26.537 回答
0

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

https://github.com/itsdrewmiller/JsonFromUri

于 2013-05-28T14:48:13.893 回答