2011-02-10 89 views
1

我正在使用从客户端脚本调用的.net脚本服务,它的工作原理非常好。.net脚本Web服务:__type属性

唯一的问题是它会为每个返回的对象生成一个'__type'属性,这是我不需要或不需要的。
我见过这个几个帖子在网上,而据我所知,只有“变通”这个:

  • 一些人建议躲在参数少c'tor返回类型为'内部保护',

  • 其他人建议不要使用[ScriptMethod]标记,而是用JSON手动输出结果并返回一个字符串。

我想知道是否有另一个更好的解决方案。顺便说一句,这个属性用于什么呢?
我附上了服务方法和生成的JSON。

方法:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] 
public IEnumerable<EmployeePO> GetEmployeesForDepartment(int DepartmentId) 
{ 

     return new AdministrationController().GetEmployeesForDepartment(DepartmentId); 

} 

JSON返回:

{"d":[{"__type":"Application.Controllers.PresentationObjects.EmployeePO","Positions":[{"__type":"Application.Controllers.PresentationObjects.PositionPO","Id":4,"Name":"Employee: 1test Position 1","IsPriority":false,"WarningThreshold":50,"CriticalThreshold":60,"CurrentWaitingTime":-1,"Passengers":[],"Qualifications":[... 
+0

你为什么在意?你不能忽略它吗?当然是 – 2011-02-13 00:37:42

+1

,但使用JSON的重点在于让对象尽可能轻。这额外的属性只是我的对象额外的重量。 – 2011-02-13 07:45:05

回答

3

行,所以我结束了从JHON莫里森采取咨询,张贴在@Kid链接TO-
我定义我返回类的所有参数少的构造函数作为受保护的内部,并且确实的伎俩问题。
在我实际需要创建我创建了一个工厂方法,像这样空物体的情况:

public class MyClass 
    { 
     public int Id { get; set; } 
     /*...*/ 

     public MyClass(int id): 
     { 
      Id = id; 
     } 


     public static MyClass CreateNewZonePO() 
     { 
      return new MyClass(); 
     } 

     //parameterless c'tor for serialization's sake 
     //it's protected internal in order to avoid the "__type" attribute when returned from a web service. see http://stackoverflow.com/questions/4958443/net-script-web-services-type-attribute 
     protected internal MyClass() 
     { 

     } 
    } 

@孩子的回答也工作了,但它看起来更清洁,以我这样。

2

我注意到,匿名类型返回的对象不产生__type属性都没有。由于不同的原因,我已经返回了一些这样的对象,JavaScript不关心,它喜欢匿名类型。所以我想我会开始转换许多其他类型将它们转换为所有对象继承的基础对象。服务层将处理此问题,因为我喜欢传递强类型,并且不希望将其转换为最后一分钟。这个演员是否需要时间?大概。这值得么?哎呀,我不知道。我同意,为了安全起见,这个信息不应该在那里。来吧微软。

0

如果将返回类型从IEnumerable<EmployeePO>更改为IEnumerable<Object>__type字段将不会添加到JSON字符串中。

0

我做了一点不同,对我来说是一个小清洁剂。 (我没有试图从以前的答案中拿走,只是试图增加/减少所需的编码量。)

public class MyClass 
{ 
    private MyClass(int id) { } //needs to have a constructor with at least one parameter passed to it. Update: looks like this is not needed. I still need to test this some more though. 

    protected internal MyClass() { } //this actually drives the restriction on the JSON return of the __type attribute and is an overload constructor 
}