JSON解析与angularjs MVC 4个Web API [英] Json parsing in MVC 4 web api with angularjs

查看:166
本文介绍了JSON解析与angularjs MVC 4个Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共部分类用户
{
    公众的System.Guid用户ID {搞定;组; }
    公众可空<&的System.Guid GT;角色ID {搞定;组; }
    公众可空<长> MembershipNo {搞定;组; }
    公共字符串用户名{获得;组; }
    公共字符串密码{搞定;组; }
    公共字符串名字{获得;组; }
    公共字符串名字{获得;组; }
    公共字符串性别{搞定;组; }
    公共字符串Emaiil {搞定;组; }
    公众可空<&小数GT; MobileNo {搞定;组; }
    公共字符串描述{搞定;组; }
    公众可空<&的System.Guid GT; ModifiedBy {搞定;组; }
    公众可空<&System.DateTime的GT; ModifiedDate {搞定;组; }
    公共虚拟角色角色{搞定;组; }
 }

这是我的表,其中与DB的角色表相关DB命名为用户

(你可以在上面看到底最后一个虚拟行)

现在我的问题很简单。我使用angulars $ http.get()方法来调用我的Web API中的MVC 4.当我叫它,它被连接,并获取所需的记录,但它不会引发正确的结果回到.js文件或控制器。
在.js文件一边,我遇到错误。每一次,它执行.error(jsonResult,配置,标题,状态)。

当我跳到上JsonResult,它表明我下面的错误。

 对象
    ExceptionMessage道:'ObjectContent`1类型没有序列化内容类型应用/ JSON的;字符集= UTF-8响应主体。
    ExceptionType:System.InvalidOperationException
    的InnerException:对象
    ExceptionMessage:检测到财产的角色型自我循环引用
    'System.Data.Entity.DynamicProxies.Role_82CA96EA045B1EB47E58B8FFD4472D86502EEA79837B4AE3AD705442F6236E58'.
    路径Role.Users [0]'。
    ExceptionType:Newtonsoft.Json.JsonSerializationException
    消息:发生了错误。

我不知道什么是错在这里。难道是JSON解析错误的东西?如果是这样,我已经听到和读到,在.NET手柄的WebAPI或引发JSON本身。

的文章

我的调用发生过

  $ http.get(apiUrl).success(功能(jsonResult,头,配置,状态){    调试器;
    变种数= parseInt函数(jsonResult.membershipNo)+ 1;    $ scope.membershipNo =M+编号;})
.error(功能(jsonResult,头,配置,状态){
    调试器;
    toastr.error('出事了联系管理员!!');
});

编辑:

一件事提了,.CS的一面,当我取单细胞值(DB /表),它就会返回到.success()调用,但是当我获取特定行或所有行,它就会被退回。错误()调用。我使用的是实体frameworkd 6.1.1。并通过EF-6.1.1产生上面的类。结果搜索结果

 公共部分类角色
{
公共角色()
{
    this.Permissions =新的List<&许可GT;();
    this.Users =新的List<使用者>();
}公众的System.Guid角色ID {搞定;组; }
公共字符串角色名{获得;组; }
公共字符串描述{搞定;组; }
公众可空<&的System.Guid GT; ModifiedBy {搞定;组; }
公众可空<&System.DateTime的GT; ModifiedDate {搞定;组; }
公共虚拟的ICollection<&许可GT;权限{搞定;组; }
公共虚拟的ICollection<使用者>用户{搞定;组; }
}


解决方案

你可以解决2个简单的步骤

第一步:创建globalConfig类,您可以设置忽略ReferenceLoopHandling( http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm ),如果你装箱JS应用程序,你可以设置以及删除XML formaters,总是得到的WebAPI回报JSON字符串是有用的调试。因此,在您app_start文件夹中添加类GlobalConfig象下面这样:

 公共类GlobalConfig
  {
                    公共静态无效CustomizeConfig(HttpConfiguration配置)
                    {
                        //删除的Xml格式化。这意味着,当我们从一个浏览器访问一个端点,
                        //而不是返回的XML,它将返回JSON。
                        //这是可选                        config.Formatters.Remove(config.Formatters.XmlFormatter);
                       GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
    Newtonsoft.Json.ReferenceLoopHandling.Ignore;                    }
}

第二步:在Global.asax中设置的自定义配置做到这一点请在下面添加code到方法的Application_Start():

  GlobalConfig.CustomizeConfig(GlobalConfiguration.Configuration);

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; }
 }

This is my table in DB named Users which is associated with Roles table of DB (as you can see last virtual row at the end above)

Now My problem is simple. I'm using angulars $http.get() method to call my Web Api in MVC 4. When i call it, it gets connected and fetches desired record but it doesn't throw proper result back to .js file or controller. At .js side I run into error. Every time, it executes .error(jsonResult,config,header,status) .

When I jump on to JsonResult, it shows me below error.

    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."

I don't know what's wrong here. Is it json parsing error or something? if so, I've heard and read the articles that webapi in .net handles or throws json itself.

My call happens through

 $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!!!');
});

Edited:

One more thing to mention, .CS side when I fetch single cell value (from DB/table) , it gets returned back to .success() call but when i fetch particular row or all rows, it gets returned to .error() call. I'm using entity frameworkd 6.1.1. and above class is generated by 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; }
}

解决方案

Hi you can solve that in 2 easy steps

First Step: Create globalConfig class where you can set ignoring ReferenceLoopHandling (http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm) and if you crating js app you can set as well to remove xml formaters and always get return from Webapi as JSON string is usefull for debugging. So in your app_start folder add class GlobalConfig like below:

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;

                    }
}

Second Step: In Global.asax set your custom configuration to do that please add code below to method Application_Start():

 GlobalConfig.CustomizeConfig(GlobalConfiguration.Configuration);

这篇关于JSON解析与angularjs MVC 4个Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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