如何将camelCase Json发送到c# Web Api以匹配Pascal属性而不会出错

本文关键字:Pascal 属性 出错 Api Web camelCase Json | 更新日期: 2023-09-27 18:13:23

目前我正在使用这个JsonFormatter向客户端发送骆驼大小写数据

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
                new CamelCasePropertyNamesContractResolver();

WebApiConfig

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Web.Http;

namespace AlumCloud
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            ((Newtonsoft.Json.Serialization.DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
            new CamelCasePropertyNamesContractResolver();
        }
    }
}

一切都很完美,我的数据在客户端收到了预期的完美。

现在,是时候开始向服务器发送数据了,我使用

C# Web Api in the .NET platform.

这是POST函数,我试图将camel case JSON数据与一个c#对象一起发布,为了清晰起见,我已经删除了大部分代码。

WebApi Controller

namespace AlumCloud.Controllers
{
    [Authorize]
    public class HorizontalController : AlumCloudWebApiBaseController
    {
        public async Task<HttpResponseMessage> Post(Horizontal h)
        {
            string update = HttpContext.Current.Request.QueryString["a"];
            int ownerID = 0; ;
            HttpResponseMessage res = null;
            InsertHorizontalHelper insertRes = null;
            if (!int.TryParse(HttpContext.Current.Request.QueryString["id"], out ownerID))
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, "Provide the id of the horizontal owner");
            };
            if (h.CompID < 1)
            {
                if (h.Sitelines.TopCompID > 0)
                {
                    h.CompID = h.Sitelines.TopCompID;
                };
            }
            switch (update)
            {

水平对象的属性是这样的,它们是Pascal case

c#客户对象我想映射属性从JSON到c#

namespace CADDL.DataTransfer.Tables
{
    [XmlType(Namespace = "urn:DataObjects")]
    [XmlRoot(Namespace = "urn:DataObjects")]
    [Serializable]
    public class Horizontal : ColumnInfo, IHorizontal
    {

        [ColumnAttributes("ID", false, "int")]
        public int ID { get; set; }
        [ColumnAttributes("Position", false, "byte")]
        public byte Position { get; set; }
        [ColumnAttributes("Name", false, "string")]
        public string Name { get; set; }
        [ColumnAttributes("IsFiller", false, "bool")]
        public bool IsFiller { get; set; }
        [ColumnAttributes("HorizontalNote", false, "string")]
        public string HorizontalNote { get; set; }
        [ColumnAttributes("SizeID", false, "int")]
        public int SizeID { get; set; }
        [ColumnAttributes("WidthInches", false, "decimal")]
        public decimal WidthInches { get; set; }
        [ColumnAttributes("HeightInches", false, "decimal")]

<

我的错误/strong>

{"message":"An error has occurred.","exceptionMessage":"Object reference not set to an instance of an object.","exceptionType":"System.NullReferenceException","stackTrace":"   at AlumCloud.Controllers.HorizontalController.<Post>d__0.MoveNext() in D:''Users''Erik Little''Documents''visual studio 2015''Projects''AlumCloud''AlumCloud''Controllers''CAD''HorizontalController.cs:line 28'r'n--- End of stack trace from previous location where exception was thrown ---'r'n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)'r'n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)'r'n   at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()'r'n--- End of stack trace from previous location where exception was thrown ---'r'n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)'r'n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)'r'n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()'r'n--- End of stack trace from previous location where exception was thrown ---'r'n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)'r'n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)'r'n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()'r'n--- End of stack trace from previous location where exception was thrown ---'r'n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)'r'n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)'r'n   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()'r'n--- End of stack trace from previous location where exception was thrown ---'r'n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)'r'n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)'r'n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}

我的问题是。

  1. 为什么我的水平c#对象总是空的,因为JSON是骆驼大小写和它匹配的属性是Pascal大小写?
  2. 从JSON到c#对象的属性映射器必须是相同的情况下,以便为值设置?
  3. 解决此问题的全局方法是什么,以便我不必在每个新的Web Api控制器中添加属性设置?

为了清楚起见,你在每个属性上看到的属性都是我的数据层的,因为当请求数据时,它们不会在这个实例中使用

如何将camelCase Json发送到c# Web Api以匹配Pascal属性而不会出错

对象被客户端接收和在服务器上处理的方式需要两个不同的对象来使生活更容易,所以我创建了一个名为客户端请求的文件夹,因此没有名称冲突,我从客户端大小命名了水平类HorizontalRequest,但只有满足客户端所需的属性。

服务器上的类对象比接收JSON请求所需的要大一些,所以当客户端发送数据时,服务器对象比需要的大20倍,我只创建像HorizontalRequest这样的类,裸骨,没有属性,只有属性。