簡體   English   中英

如何在ASP.NET Web API中隱藏某些遞歸屬性

[英]How can I hide some of recursive properties in 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 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)"
        }
    }
}

用戶類別

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

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

您堆棧中最深的錯誤是:

“對對象'UserStatus',數據庫'BOOKSWAP',模式'dbo'的SELECT權限被拒絕。”

因此,我猜您應該決定如何處理數據庫權限,因為這可能是整個堆棧中的關鍵問題。

鏈接應該會有所幫助。

JsonIgnore屬性會有所幫助嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM