我正在尝试将我的对象转换为 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)rn at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)rn at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)rn at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)rn at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)rn at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)rn at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)rn at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)rn--- End of stack trace from previous location where exception was thrown ---rn at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()rn at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)rn 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)rn at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)rn at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)rn at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()rn at System.Data.SqlClient.SqlDataReader.get_MetaData()rn at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)rn 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)rn 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)rn at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)rn at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)rn at System.Data.SqlClient.SqlCommand.ExecuteReader()rn at Bookswap.Models.UserStatusBusinessLayer.get_userStatuses() in D:\University\Fall-17\FYP\Project\Web\Bookswap\Bookswap\Models\UserStatusBusinessLayer.cs:line 19rn at Bookswap.ViewModels.User.get_userStatus() in D:\University\Fall-17\FYP\Project\Web\Bookswap\Bookswap\ViewModels\User.cs:line 40rn at GetuserStatus(Object )rn at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
}
}
}
用户类
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();
}
}
}
}
网页 API 控制器方法
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)));
}
JsonIgnore 属性会有所帮助吗?
堆栈中最深的错误是:
"对象'UserStatus'、数据库'BOOKSWAP'、架构'dbo'的 SELECT 权限被拒绝。">
所以我想你应该决定如何处理数据库权限,因为它可能是整个堆栈中的关键问题。
此链接应该会有所帮助。