C# 如何在ASP.NET Web API中隐藏某些递归属性

C# 如何在ASP.NET Web API中隐藏某些递归属性,c#,asp.net-mvc,recursion,asp.net-web-api,C#,Asp.net Mvc,Recursion,Asp.net Web Api,我正在尝试将我的对象转换为json,由于某些属性,这个对象有一些无限递归循环,我能做些什么来不显示这些属性,或者不将这些属性转换为json?在我将对象转换为json时,会产生这种错误 错误 { "$id": "1", "Message": "An error has occurred.", "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for co

我正在尝试将我的对象转换为json,由于某些属性,这个对象有一些无限递归循环,我能做些什么来不显示这些属性,或者不将这些属性转换为json?在我将对象转换为json时,会产生这种错误

错误

{
    "$id": "1",
    "Message": "An error has occurred.",
    "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null,
    "InnerException": {
        "$id": "2",
        "Message": "An error has occurred.",
        "ExceptionMessage": "Error getting value from 'userStatus' on 'Bookswap.ViewModels.User'.",
        "ExceptionType": "Newtonsoft.Json.JsonSerializationException",
        "StackTrace": "   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()",
        "InnerException": {
            "$id": "3",
            "Message": "An error has occurred.",
            "ExceptionMessage": "The SELECT permission was denied on the object 'UserStatus', database 'BOOKSWAP', schema 'dbo'.",
            "ExceptionType": "System.Data.SqlClient.SqlException",
            "StackTrace": "   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n   at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader()\r\n   at Bookswap.Models.UserStatusBusinessLayer.get_userStatuses() in D:\\University\\Fall-17\\FYP\\Project\\Web\\Bookswap\\Bookswap\\Models\\UserStatusBusinessLayer.cs:line 19\r\n   at Bookswap.ViewModels.User.get_userStatus() in D:\\University\\Fall-17\\FYP\\Project\\Web\\Bookswap\\Bookswap\\ViewModels\\User.cs:line 40\r\n   at GetuserStatus(Object )\r\n   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
        }
    }
}

堆栈中最深的错误是:

对对象“UserStatus”、数据库“BOOKSWAP”、架构“dbo”的SELECT权限被拒绝

所以我想您应该决定如何处理数据库权限,因为这可能是整个堆栈中的关键问题


链接应该会有帮助。

是否会属性帮助?

我不知道为什么会在深层显示该错误,我已经修复了该错误。谢谢,伙计,这很好:)
using Bookswap.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Bookswap.ViewModels
{
    public class User
    {
        public int id { get; set; }

        public string firstName { get; set; }

        public string lastName { get; set; }

        public string email { get; set; }

        public string contact { get; set; }

        public string password { get; set; }

        public string username { get; set; }

        public int cityId { get; set; }

        public int userStatusId { get; set; }

        public int userTypeId { get; set; }

        public DateTime time { get; set; }

        public DateTime dateOfBirth { get; set; }

        public UserStatus userStatus
        {
            get
            {
                UserStatusBusinessLayer us = new UserStatusBusinessLayer();
                return us.userStatuses.FirstOrDefault(x => x.id == userStatusId);
            }
        }

        public UserType userType
        {
            get
            {
                UserTypeBusinessLayer us = new UserTypeBusinessLayer();
                return us.userTypes.FirstOrDefault(x => x.id == userTypeId);
            }
        }

        public Country country
        {
            get
            {
                return new CountryBusinessLayer().countries.FirstOrDefault(x => x.id == (new CityBusinessLayer().cities.FirstOrDefault(y => y.id == cityId).countryId));
            }
        }

        public City city
        {
            get
            {
                return new CityBusinessLayer().cities.FirstOrDefault(y => y.id == cityId);
            }
        }

        public List<UserMedia> userMedia
        {
            get
            {
                return new UserMediaBusinessLayer().userMedias.Where(x => x.userId == id).ToList();
            }
        }

        public List<Book> books
        {
            get
            {
                return new BookBusinessLayer().books.Where(x => x.userId == id).OrderByDescending(x => x.id).ToList();
            }
        }

        public List<Review> reviews
        {
            get
            {
                return new ReviewBusinessLayer().reviews.Where(x => x.userId == id).ToList();
            }
        }

        public int coins
        {
            get
            {
                CoinsBusinessLayer cbl = new CoinsBusinessLayer();
                return cbl.coins.Where(x => x.userId == id).Sum(x => x.coinValue);
            }
        }

        public List<Conversation> conversations
        {
            get
            {
                return new ConversationBusinessLayer().conversations.Where(x => x.useroneid == id || x.usertwoid == id).OrderByDescending(x => x.conversationReplies.OrderByDescending(y => y.time) ).ToList();
            }
        }
    }
}
public ViewModels.User Post(string identity, string password)
{
    return new Models.UserBusinessLayer().users.FirstOrDefault(x => (x.email == identity && x.password == Data.Crypto.MD5Hash(password)) || (x.username == identity && x.password == Data.Crypto.MD5Hash(password)) || (x.contact == Data.Crypto.RemoveSpaceFromContact(identity) && x.password == Data.Crypto.MD5Hash(password)));
}