【问题标题】:Json parsing in MVC 4 web api with angularjs使用angularjs在MVC 4 web api中解析Json
【发布时间】:2014-09-10 23:49:21
【问题描述】:
public partial class User
{
    public System.Guid UserId { get; set; }
    public Nullable<System.Guid> RoleId { get; set; }
    public Nullable<long> MembershipNo { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public string Emaiil { get; set; }
    public Nullable<decimal> MobileNo { get; set; }
    public string Description { get; set; }
    public Nullable<System.Guid> ModifiedBy { get; set; }
    public Nullable<System.DateTime> ModifiedDate { get; set; }
    public virtual Role Role { get; set; }
 }

这是我在名为 Users 的 DB 中的表,它与 DB 的 Roles 表相关联(您可以在上面看到最后一个虚拟行)

现在我的问题很简单。我正在使用 angulars $http.get() 方法在 MVC 4 中调用我的 Web Api。当我调用它时,它会连接并获取所需的记录,但它不会将正确的结果返回给 .js 文件或控制器。 在 .js 方面我遇到了错误。每次都会执行 .error(jsonResult,config,header,status) 。

当我跳转到 JsonResult 时,它会显示以下错误。

    Object
    ExceptionMessage: "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
    ExceptionType: "System.InvalidOperationException"
    InnerException: Object
    ExceptionMessage: "Self referencing loop detected for property 'Role' with type
    'System.Data.Entity.DynamicProxies.Role_82CA96EA045B1EB47E58B8FFD4472D86502EEA79837B4AE3AD705442F6236E58'. 
    Path 'Role.Users[0]'."
    ExceptionType: "Newtonsoft.Json.JsonSerializationException"
    Message: "An error has occurred."

我不知道这里出了什么问题。是json解析错误还是什么?如果是这样,我已经听过并阅读过 .net 中的 webapi 处理或抛出 json 本身的文章。

我的电话是通过

 $http.get(apiUrl).success(function (jsonResult, header, config, status) {

    debugger;
    var number = parseInt(jsonResult.membershipNo) + 1;

    $scope.membershipNo = "M" + number;

})
.error(function (jsonResult, header, config, status) {
    debugger;
    toastr.error('Something went wrong ! Contact Administrator!!!');
});

编辑:

还有一点要提一下,.CS 端当我获取单个单元格值(从 DB/表)时,它会返回到 .success() 调用,但是当我获取特定行或所有行时,它会返回到 .cs 端。错误()调用。我正在使用实体框架 6.1.1。及以上类由 EF-6.1.1 生成。


public partial class Role
{
public Role()
{
    this.Permissions = new List<Permission>();
    this.Users = new List<User>();
}

public System.Guid RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual ICollection<Permission> Permissions { get; set; }
public virtual ICollection<User> Users { get; set; }
}

【问题讨论】:

  • 当 asp.net web api 尝试将您的对象序列化为 JSON 时,它看起来像一个循环引用问题,如错误Self referencing loop detected for property 'Role'中所述
  • 嗯...应该是什么解决方案?
  • 通常,当我们将对象序列化为 JSON 时,我们应该序列化视图模型对象 (DTO) 而不是您的域模型。
  • 尝试将您的域模型对象转换为 flattened 视图模型对象 (DTO):stackoverflow.com/questions/4061440/…
  • 你的角色类是什么。如果您在 Role 类中有 User 属性,请将其从序列化中排除或使用视图模型而不是域模型作为 Khanh TO sad。

标签: angularjs asp.net-mvc-4 asp.net-web-api


【解决方案1】:

您好,只需 2 个简单步骤即可解决此问题

第一步:创建 globalConfig 类,您可以在其中设置忽略 ReferenceLoopHandling (http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm),如果您创建 js 应用程序,您也可以设置删除 xml 格式化程序并始终从 Webapi 获取返回,因为 JSON 字符串对于调试很有用。因此,在您的 app_start 文件夹中添加 GlobalConfig 类,如下所示:

public class GlobalConfig
  {
                    public static void CustomizeConfig(HttpConfiguration config)
                    {
                        // Remove Xml formatters. This means when we visit an endpoint from a browser,
                        // Instead of returning Xml, it will return Json.
                        //that is optional

                        config.Formatters.Remove(config.Formatters.XmlFormatter);   
                       GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = 
    Newtonsoft.Json.ReferenceLoopHandling.Ignore;

                    }
}

第二步:在 Global.asax 中设置您的自定义配置,请在 Application_Start() 方法中添加以下代码:

 GlobalConfig.CustomizeConfig(GlobalConfiguration.Configuration);

【讨论】:

  • 此解决方案有效! @Sylwester 你能解释一下这是什么吗?我想补充一下我的知识。我几乎明白了。仍然想从你那里获得更多。
  • @all...我想知道当我想添加带有必填字段的“用户”模型(在 js 端创建)并将其扔给 .CS 时会发生什么。它会接受我的用户模型,因为我不会添加名为“角色”的“最后一个虚拟键”。 (它会接受我的用户模型 .CS 端 ---public dynamic Post(User user)????????????)
  • 我回家后会做的
【解决方案2】:

听起来像: 问题是 EF 正在使用延迟加载,该延迟加载在构建这个角色时没有实现。早期版本的 EF 默认开启延迟加载。

建议的解决方案 使用您真正需要的部分创建用户类的子集。 => 获取太多你不需要的数据是不好的做法。

【讨论】:

  • 感谢您的建议。我会记住所有的事情。是的,这是创建自定义模型的好习惯,但我很想知道出了什么问题……
猜你喜欢
  • 1970-01-01
  • 2015-05-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2012-07-27
  • 2011-08-26
  • 2018-10-21
相关资源
最近更新 更多