2

我想搜索所有使用匿名类型的地方Controllers,如下所示。

if(success) {
    returnData = JsonConvert.SerializeObject(new { Success = true, Message = "Operation completed successfully" });
}
else {
    returnData = JsonConvert.SerializeObject(new { Success = false, Message = "Operation failed" });
}

在上述情况下,returnData是 a JsonResult,它在我们的Razor视图中用于解析AJAX请求的状态。

我想在这种情况下尽量减少匿名类型的使用,因为这可能是维护问题,因为如果任何行被编写为编译器不会引发任何警告/错误,new { Succes = true, Message = "Operation completed successfully"}并且会导致客户端脚本中的运行时错误.

任何有关限制此类情况或检测此类情况的见解将不胜感激。

4

3 回答 3

4

为什么不使用“使用正则表达式”选项在解决方案/项目中搜索呢?

\bnew\s*{
于 2012-11-21T14:43:46.177 回答
2

只是不要使用匿名类型。使用您计划使用的数据创建一个新的具体类型:

public class JSONMessage
{
    public string Message { get; set; }
    public bool Success { get; set; }
}

然后这些行可以更改为:

if(success) {
    returnData = JsonConvert.SerializeObject(new JSONMessage(){ Success = true, Message = "Operation completed successfully" });
}
else {
    returnData = JsonConvert.SerializeObject(new JSONMessage(){ Success = false, Message = "Operation failed" });
}
于 2012-11-21T14:55:11.780 回答
1

如何结束 json 调用,以便您可以有运行时错误/断言:

首先是从这里检测匿名的扩展:Determining If a Type is an Anonymous Type

public static class TypeExtension {

    public static Boolean IsAnonymousType(this Type type) {
        var hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Count() > 0;
        var nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
        var isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;    
        return isAnonymousType;
    }
}

然后使用它作为你的新方法。

 public static object JsonSeralize(object obj)
   {
      Debug.Assert(!obj.getType().IsAnonymousType());     
      return JsonConvert.SerializeObject(obj);
   }

现在您可以轻松地直接搜索非法呼叫的地方JsonConvert.SerializeObject

于 2012-11-21T15:30:26.780 回答