ASP.NET WebAPI 与 MVC 在参数的 json(反)序列化方面存在细微的行为偏差

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

假设我们有以下简单的 ajax 调用:

 $.ajax({
    url: "/somecontroller/someaction",
    data: JSON.stringify({
        someString1: "",
        someString2: null,
        someArray1: [],
        someArray2: null
    }),
    method: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8"
})
    .done(function (response) {
        console.log(response);
    });

ajax 调用的目标是 asp.net Controller 的操作。 asp.net 网站在处理 json 序列化时具有默认(“工厂”)设置,唯一的调整是 Newtonsoft.Json.dll 通过 nuget 安装,因此 web.config 包含以下部分:

   <dependentAssembly>
       <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
       <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
   </dependentAssembly>

global.asax.cs 中的 webapi 和 mvc 的配置部分保持不变。说了这么多,我注意到如果 Controller “somecontroller”是一个 webapi Controller :

public class FooController : ApiController
{
    public class Some
    {
        public string SomeString1 { get; set; }
        public string SomeString2 { get; set; }
        public long[] SomeArray1 { get; set; }
        public long[] SomeArray2 { get; set; }
    }

    [HttpPost]
    public IHttpActionResult Bar([FromBody] Some entity)
    {
        return Ok(new {ping1 = (string) null, ping2 = "", ping3 = new long[0]});
    }
}

那么在 C# 世界中“someaction”方法中接收到的数据如下所示:

    entity.someString1: "",
    entity.someString2: null,
    entity.someArray1: [],
    entity.someArray2: null

但是,如果 Controller 是 mvc Controller (准确地说是 mvc4):

public class FooController : System.Web.Mvc.Controller
{
    public class Some
    {
        public string SomeString1 { get; set; }
        public string SomeString2 { get; set; }
        public long[] SomeArray1 { get; set; }
        public long[] SomeArray2 { get; set; }
    }

    [HttpPost]
    public System.Web.Mvc.JsonResult Bar([FromBody] Some entity)
    {
        return Json(new { ping1 = (string)null, ping2 = "", ping3 = new long[0] });
    }
}

然后在方法内的 csharp 世界中接收到的数据如下所示:

    entity.someString1: null,
    entity.someString2: null,
    entity.someArray1: null,
    entity.someArray2: null

很明显,当涉及到空数组和空字符串时,webapi 和 mvc Controller 在参数反序列化的工作方式方面存在差异。我设法解决了 MVC Controller 的怪癖,以便对空字符串和空数组强制执行“webapi”行为(为了完整性,我将在最后发布我的解决方案)。

我的问题是这样的:

为什么反序列化方面首先存在这种偏差?

考虑到默认的 mvc 设置为错误留下了多少空间,这些错误在操作中清晰一致地识别和修复是非常伤脑筋的,所以我不能认为这仅仅是为了“方便”/dto-level。

附录:对于任何感兴趣的人来说,在将参数输入到操作方法之前,我如何强制 mvc Controller 以“webapi”方式运行:

  //inside Application_Start
  ModelBinders.Binders.DefaultBinder = new CustomModelBinder_Mvc(); 
  ValueProviderFactories.Factories.Remove(
      ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault()
  ); 
  ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory_Mvc());

实用类:

  using System.Web.Mvc;

  namespace Project.Utilities
  {
      public sealed class CustomModelBinder_Mvc : DefaultModelBinder //0
      {
          public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
          {
              bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
              Binders = new ModelBinderDictionary { DefaultBinder = this };
              return base.BindModel(controllerContext, bindingContext);
          }
      }
      //0 respect empty ajaxstrings aka "{ foo: '' }" gets converted to foo="" instead of null  http://stackoverflow.com/a/12734370/863651
  }

还有

    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using Newtonsoft.Json.Serialization;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Dynamic;
    using System.Globalization;
    using System.IO;
    using System.Web.Mvc;
    using IValueProvider = System.Web.Mvc.IValueProvider;
    // ReSharper disable RedundantCast

    namespace Project.Utilities
    {
        public sealed class JsonNetValueProviderFactory_Mvc : ValueProviderFactory //parameter deserializer
        {
            public override IValueProvider GetValueProvider(ControllerContext controllerContext)
            {
                if (controllerContext == null)
                    throw new ArgumentNullException(nameof(controllerContext));
    
                if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
                    return null;
    
                var jsonReader = new JsonTextReader(new StreamReader(controllerContext.HttpContext.Request.InputStream));
                if (!jsonReader.Read())
                    return null;
    
                var jsonObject = jsonReader.TokenType == JsonToken.StartArray //0
                    ? (object)JsonSerializer.Deserialize<List<ExpandoObject>>(jsonReader)
                    : (object)JsonSerializer.Deserialize<ExpandoObject>(jsonReader);
    
                return new DictionaryValueProvider<object>(AddToBackingStore(jsonObject), InvariantCulture); //1
            }
            private static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture;
            private static readonly JsonSerializer JsonSerializer = new JsonSerializer //newtonsoft
            {
                Converters =
                {
                    new ExpandoObjectConverter(),
                    new IsoDateTimeConverter {Culture = InvariantCulture}
                }
            };
            //0 use jsonnet to deserialize object to a dynamic expando object  if we start with a [ treat this as an array
            //1 return the object in a dictionary value provider which mvc can understand
    
            private static IDictionary<string, object> AddToBackingStore(object value, string prefix = "", IDictionary<string, object> backingStore = null)
            {
                backingStore = backingStore ?? new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
    
                var d = value as IDictionary<string, object>;
                if (d != null)
                {
                    foreach (var entry in d)
                    {
                        AddToBackingStore(entry.Value, MakePropertyKey(prefix, entry.Key), backingStore);
                    }
                    return backingStore;
                }
    
                var l = value as IList;
                if (l != null)
                {
                    if (l.Count == 0) //0 here be dragons
                    {
                        backingStore[prefix] = new object[0]; //0 here be dragons
                    }
                    else
                    {
                        for (var i = 0; i < l.Count; i++)
                        {
                            AddToBackingStore(l[i], MakeArrayKey(prefix, i), backingStore);
                        }
                    }
                    return backingStore;
                }
    
                backingStore[prefix] = value;
                return backingStore;
            }
    
            private static string MakeArrayKey(string prefix, int index) => $"{prefix}[{index.ToString(CultureInfo.InvariantCulture)}]";
            private static string MakePropertyKey(string prefix, string propertyName) => string.IsNullOrEmpty(prefix) ? propertyName : $"{prefix}.{propertyName}";
        }
        //0 here be dragons      its vital to deserialize empty jsarrays "{ foo: [] }" to empty csharp array aka new object[0]
        //0 here be dragons      without this tweak we would get null which is completely wrong
    }

最佳答案

Why does this deviation in regards to deserialization exist in the first place?

历史。

何时 ASP.NET MVC首次创建于 2009 年,它使用原生 .NET JavaScriptSerializer处理 JSON 序列化的类。当Web API三年后,作者决定改用日益流行的 Json.Net 序列化器,因为它比旧的 JavaScriptSerializer 更加健壮且功能齐全。然而,他们显然认为出于向后兼容性的原因,他们无法更改 MVC 来匹配 - 依赖特定 JavaScriptSerializer 行为的现有项目在升级时会意外中断。因此,该决定造成了 MVC 和 Web API 之间的差异。

ASP.NET MVC Core ,MVC和Web API的内部已经统一并使用Json.Net。

关于ASP.NET WebAPI 与 MVC 在参数的 json(反)序列化方面存在细微的行为偏差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43253528/

相关文章:

python - ElasticSearch:TypeError:预期的字符串还是缓冲区?

asp.net-mvc - ASPNETCORE 在 VS 2015 中本地工作,但发布到 Azure 时出现错误 500

c# - MVC Post 导致 QueryString 在重新加载同一 View 时丢失

c# - 在 aspx 上获取 ascx

java - 我有更新电影的更新方法。但是当我在 postman 中提供数据时,我输入一个字段,然后其余字段获取空值

mysql - 如何使用 mysql 原生 json 函数生成嵌套的 json 对象?

asp.net-mvc - DRY 与 MVC 和 View 模型的安全性和可维护性

asp.net-mvc - ASP.NET MVC筛选产生列表/网格

asp.net - 编译调试 ="false"和 Release模式有什么区别?

c# - 无法在 .Net (C#) 中使用 ajax 发送基本的非 MVC 表单