的ASP.NET Web API与下划线序列 [英] ASP.NET Web API is serializing with underscore

查看:351
本文介绍了的ASP.NET Web API与下划线序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ApiController以下简单的code:

I have the following simple code in an ApiController:

public Version Get()
{
  var version = new System.Version(1, 1, 0, 0);
  return version;
}

这将导致以下内容:

which results in the following:

JSON

{"_Major":1,"_Minor":1,"_Build":0,"_Revision":0}

XML

<Version xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/System">
  <_Build>0</_Build>
  <_Major>1</_Major>
  <_Minor>1</_Minor>
  <_Revision>0</_Revision>
</Version>

请注意,性能与 _ pceded $ P $。综观<$ C的类定义$ C>版本 所有这些属性是吸气剂而已,我怀疑有事做,为什么序列化添加 _ 。我也试着找资料这里 的,为什么发生这种情况,但所有它说,只读属性默认情况下,系列化。

Please note the properties are preceded with an _. Looking at the class definition of Version all those properties are Getters only, which I suspect has something to do with why the serialization is adding the _. I also tried to find information here on why this is happening, but all it says that Read-only properties are serialized by default.

问题是,下划线是搞乱客户端上的反序列化,并导致版本 0.0.0.0

The problem is that the underscore is messing up the deserialization on the client and resulting in Version 0.0.0.0.

这是一个CLR类,我不能重写,所以我怎么能删除下划线所以它在客户端上正确地反序列化?

This is a CLR class, which I can't override, so how can I remove the underscore so it deserializes correctly on the client?

推荐答案

在默认情况下的Web API序列化的具有[Serializable]属性(例如版)类型的字段。我不是它的一个巨大的风扇这就是为什么Json.NET默认不这样做,但是这是在Web API人想要的东西。

By default Web API serializes the fields of types that have a [Serializable] attribute (e.g. Version). I'm not a huge fan of it which is why Json.NET doesn't do it by default, but that's what the Web API guys wanted.

这将停止网络API以JSON这样做:

This will stop Web API doing it in JSON:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new DefaultContractResolver();

这篇关于的ASP.NET Web API与下划线序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆