![](/img/trans.png)
[英]Self referencing loop detected - Getting back data from WebApi to the browser
[英]Self referencing loop detected while reading data from sql server
我正在嘗試使用以下代碼每秒從數據庫中讀取數據:
public class DBChangeService : DelegatingHandler, IHostedService
{
private Timer _timer;
public SqlDependencyEx _sqlDependency;
private readonly IHubContext<SignalServer> _hubcontext;
private readonly IServiceScopeFactory _scopeFactory;
string connectionString = "";
public IConfiguration Configuration { get; }
public DBChangeService(IConfiguration configuration, IHubContext<SignalServer> hubcontext, IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
_hubcontext = hubcontext;
Configuration = configuration;
connectionString = Configuration.GetConnectionString("DefaultConnection");
}
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(Heartbeat, null, 0, 1000);
return Task.CompletedTask;
}
public void Heartbeat(object state)
{
_hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps());
}
public async Task<List<SomeModel>> SBSystemApps()
{
var data = new List<SomeModel>();
using (var scope = _scopeFactory.CreateScope())
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string commandText = @"SELECT
a.name as AppName,
a.state as AppState,
a.created_at as AppCreatedAt,
a.updated_at as AppUpdatedAt,
a.foundation as AppFoundation,
s.name as SpaceName,
o.name as OrgName
FROM
apps as a
INNER JOIN
spaces as s ON a.space_guid = s.space_guid
INNER JOIN
organizations as o ON s.org_guid = o.org_guid
where s.name = 'system' and o.name = 'system' and a.foundation = 2";
try
{
SqlCommand cmd = new SqlCommand(commandText, connection);
await connection.OpenAsync();
using (DbDataReader reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var sqlresult = new SomeModel
{
AppName = reader["AppName"].ToString(),
AppState = reader["AppState"].ToString(),
AppCreatedAt = Convert.ToDateTime(reader["AppCreatedAt"]),
AppUpdatedAt = Convert.ToDateTime(reader["AppUpdatedAt"]),
AppFoundation = Convert.ToInt32(reader["AppFoundation"]),
SpaceName = reader["SpaceName"].ToString(),
OrgName = reader["OrgName"].ToString(),
};
data.Add(sqlresult);
}
}
}
finally
{
connection.Close();
}
return data;
}
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
//Timer does not have a stop.
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
}
收到以下錯誤:
Newtonsoft.Json.JsonSerializationException:檢測到類型為“System.Runtime.CompilerServices.AsyncTaskMethodBuilder
1+AsyncStateMachineBox
1[System.Collections.Generic.List`1[TestApp.Models.SomeModel],TestApp.Services”的屬性“task”的自引用循環.DBChangeService+d__11]'。
我已經嘗試了幾乎所有可以在 StackOverflow 上找到的可能解決方案,但都沒有奏效
在啟動時:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
在我班級的標題上,我嘗試使用[JsonObject(IsReference = true)]
但沒有任何想法對我[JsonObject(IsReference = true)]
?
模型:
[JsonObject(IsReference = true)]
public partial class SomeModel
{
public string AppName { get; set; }
public string AppState { get; set; }
public DateTime AppCreatedAt { get; set; }
public DateTime AppUpdatedAt { get; set; }
public int AppFoundation { get; set; }
public string OrgName { get; set; }
public string SpaceName { get; set; }
}
_hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps());
問題是您正在使用Task
調用SendAsync
。 這不是 API 的設計用途。 您應該傳遞要使用的實際有效負載。
有多種方法可以解決這個問題。 一種是使用:
_hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps().GetAwaiter().GetResult());
盡管我建議您閱讀本指南,了解為什么它不是一個好主意。
另一種方法是更改SBSystemApps
使其同步(即返回List<T>
而不是Task<List<T>>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.